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 { ToastService } from 'src/app/services/toast.service';
import { EliminateEventPage } from 'src/app/modals/eliminate-event/eliminate-event.page';
import { ExpedientTaskModalPageNavParamsTask } from 'src/app/models/ExpedientTaskModalPage';
import { DocumentSetUpMeetingPage } from 'src/app/modals/document-set-up-meeting/document-set-up-meeting.page';
import { ExpedientTaskModalPage } from 'src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ThemeService } from 'src/app/services/theme.service'
import { RouteService } from 'src/app/services/route.service';


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

  loadedEvent: any;
  isEventEdited: boolean;
  eventBody: EventBody;
  loadedAttachments:any;
  pageId: string;
  showLoader: boolean;
  task: ExpedientTaskModalPageNavParamsTask;
  minDate: Date;
  LoadedDocument:any = null;

  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,
    public ThemeService: ThemeService
  ) {
    this.isEventEdited = false;
    this.loadedEvent = new Event();
    this.eventBody = { BodyType : "1", Text : ""};
    this.loadedEvent.Body = this.eventBody;
  }

  ngOnInit() {
    this.loadEvent();
  }

  doRefresh(ev) {
    this.loadEvent();
    ev.target.complete();
  }

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

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

  openOptions() {
  }

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

  close() {

    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)=> {

      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) {
      const loader = this.toastService.loading()

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

      const loader = this.toastService.loading()

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

  }

  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=>{
      const url: string = res.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
      const browser = this.iab.create(url,"_blank");
      browser.show();
    });
  }

  async LoadDocumentDetails() {
    
    const docId = this.loadedEvent.Attachments[ this.dicIndex].SourceId
    const applicationId: any = this.loadedEvent.Attachments[ this.dicIndex].ApplicationId
    const selectedDoc = this.loadedEvent.Attachments[ this.dicIndex]

    console.log('selectedDoc', selectedDoc)

    this.task = {
      serialNumber: '',
      taskStartDate: '',
      isEvent: true,
      workflowInstanceDataFields: {
        FolderID: '',
        Subject: selectedDoc.SourceName,
        SourceSecFsID: selectedDoc.ApplicationId || selectedDoc.ApplicationID,
        SourceType: 'DOC',
        SourceID: selectedDoc.SourceId,
        DispatchNumber: ''
      }
    }

    const modal = await this.modalController.create({
      component: ViewDocumentPage,
      componentProps: {
        trustedUrl: '',
        file: {
          title: this.task.workflowInstanceDataFields.Subject,
          url: '',
          title_link: '',
        },
        Document: this.loadedEvent.Attachments[ this.dicIndex],
        applicationId: this.task.workflowInstanceDataFields.SourceSecFsID,
        docId: selectedDoc.SourceId,
        folderId: '',
        task: this.task
      },
      cssClass: 'modal modal-desktop'
    });
    await modal.present();

  }

  async openBookMeetingModal() {

    let classs;
    if( window.innerWidth < 701) {
      classs = 'book-meeting-modal modal modal-desktop'
    } else  {
      classs = 'modal modal-desktop showAsideOptions'
    }
    const modal = await this.modalController.create({
      component: DocumentSetUpMeetingPage,
      componentProps: {
        subject: this.task.workflowInstanceDataFields.Subject,
        document: this.loadedEvent.Attachments[ this.dicIndex],
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then(res=>{
      //this.RouteService.goBack();
    });
  }

  // efetuar despacho
  async openExpedientActionsModal( taskAction: any) {

    let classs;
    if( window.innerWidth < 701) {
      classs = 'modal modal-desktop'
    } else  {
      classs = 'modal modal-desktop showAsideOptions'
    }
    const modal = await this.modalController.create({
      component: ExpedientTaskModalPage,
      componentProps: {
        taskAction: taskAction,
        task: this.task,
        seachDocuments: this.loadedEvent.Attachments[ this.dicIndex],
        aplicationId: this.loadedEvent.Attachments[ this.dicIndex].ApplicationId || this.loadedEvent.Attachments[ this.dicIndex].ApplicationID
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then( async(res)=>{});

  }

}
