import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { AlertController, ModalController, PopoverController } from '@ionic/angular';
import { Attachment } from 'src/app/models/attachment.model';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventsService } from 'src/app/services/events.service';
import { Event } from 'src/app/models/event.model';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ProcessesService } from 'src/app/services/processes.service';
import { OptsExpedientePage } from '../../popover/opts-expediente/opts-expediente.page';
import { ToastService } from 'src/app/services/toast.service';
import { EliminateEventPage } from 'src/app/modals/eliminate-event/eliminate-event.page';

@Component({
  selector: 'app-view-event',
  templateUrl: './view-event.page.html',
  styleUrls: ['./view-event.page.scss'],
})
export class ViewEventPage implements OnInit {

  loadedEvent: Event;
  isEventEdited: boolean;
  eventBody: EventBody;
  loadedAttachments:any;
  pageId: string;
  showLoader: boolean;

  minDate: Date;

  customDate:any;
  today:any;

  months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
  days = ["Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"];

  documents: Attachment[] = [];
  dicIndex = 0;

  @Input() profile:string;
  @Input() eventId: string;

  @Output() viewEventDetailDismiss = new EventEmitter<any>();

  constructor(
    private eventsService: EventsService,
    public alertController: AlertController,
    private iab: InAppBrowser,
    private processes: ProcessesService,
    private modalController: ModalController,
    public popoverController: PopoverController,
    private toastService: ToastService,
  )
  {
    this.isEventEdited = false;
    this.loadedEvent = new Event();
    this.eventBody = { BodyType : "1", Text : ""};
    this.loadedEvent.Body = this.eventBody;
  }

  ngOnInit() {

    /* console.log(this.eventId); */
    this.loadEvent();
    //this.getAttachments();
  }

  ngOnChanges(changes: any): void {
    this.loadedAttachments = null;
    this.loadEvent();
  }

  toDateString(e) {
    return new Date(e).toDateString()
  }

  openOptions() {
  }

  docIndex(index: number) {
    this.dicIndex = index;
  }

  close(){
    console.log(this.isEventEdited);

    this.viewEventDetailDismiss.emit({
      type: 'close'
    })
  }

  loadEvent() {
    this.eventsService.getEvent(this.eventId).subscribe(res => {
      console.log(res);
      this.loadedEvent = res;
      this.today = new Date(res.StartDate);
      this.customDate = this.days[this.today.getDay()]+ ", "  + this.today.getDate() +" de "  + ( this.months[this.today.getMonth()]);
    }, (error)=> {

      console.log('errer', )

      this.viewEventDetailDismiss.emit({
        type: 'close'
      })

      if(error.status == 0) {
        this.toastService.badRequest('Não é possível  visualizar este evento no modo offline')
      } else {
        this.toastService.badRequest('Este evento já não existe na sua agenda')
      }

    });
  }

  async deleteEvent() {

    if (this.loadedEvent.IsRecurring) {

    } else {
      this.eventsService.deleteEvent(this.loadedEvent.EventId, 0).subscribe(async () => {
        this.toastService.successMessage('Evento apagado');
        this.close();
      });
    }

  }

  async deleteRecurringEvent() {

    const modal = await this.modalController.create({
      component: EliminateEventPage,
      componentProps: {},
      cssClass: 'discart-expedient-modal',

    });
    await modal.present();
    modal.onDidDismiss().then((res) => {

    });

  }


  async editEvent() {
    this.viewEventDetailDismiss.emit({
      type: 'edit',
      event: this.loadedEvent
    })
  }

  viewDocument(sourceId) {
    this.processes.GetDocumentUrl(sourceId, '8').subscribe(res=>{
      console.log(res);
      const url: string = res.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
      const browser = this.iab.create(url,"_blank");
      browser.show();

    });
  }

  async openTaskOptions() {

    const doc = this.loadedAttachments[ this.dicIndex];

    let customTask;

    if(doc.ApplicationID == 361 || doc.ApplicationId == 361) {
      customTask = {
        serialNumber: doc.DispatchNumber,
        taskStartDate: doc.DateDispatch,
        isEvent: true,
        workflowInstanceDataFields: {
          FsId: doc.ApplicationID,
          FolderID: null,
          DocId: doc.DispatchNumber,
          Subject: doc.Assunto
        },
      }
    } else if (doc.ApplicationID == 8 || doc.ApplicationId == 8) {
      customTask = {
        serialNumber: doc.DocId,
        taskStartDate: doc.DocDate,
        isEvent: true,
        workflowInstanceDataFields: {
          FsId: doc.ApplicationID || doc.ApplicationId,
          FolderID: null,
          DocId: doc.DocId,
          Subject: doc.Assunto
        }
      }
    }

    console.log(doc)
    customTask.Status = ''

    const popover = await this.modalController.create({
      component: OptsExpedientePage,
      cssClass: 'model aside-modal search-submodal',
      componentProps: {
        fulltask: customTask,
        task: customTask
      },
      //translucent: true
    });
    return await popover.present();
  }

}
