import { Component, OnInit } from '@angular/core';
import { AlertController, ModalController, PopoverController } from '@ionic/angular';
import { EventBody } from 'src/app/models/eventbody.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { Event } from '../../../models/event.model';
import { EditEventPage } from '../edit-event/edit-event.page';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ProcessesService } from 'src/app/services/processes.service';
import { OptsExpedientePage } from 'src/app/shared/popover/opts-expediente/opts-expediente.page';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastService } from 'src/app/services/toast.service';
import { EliminateEventPage } from 'src/app/modals/eliminate-event/eliminate-event.page';
import { Location } from '@angular/common'

@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;

  profile:string;
  eventId:string;
  caller:string;
  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"];

  dicIndex = 0;
  isModal = false
  header = true

  constructor(
    private modalController: ModalController,
   /*  private navParams: NavParams, */
    private eventsService: EventsService,
    private attachmentsService: AttachmentsService,
    public alertController: AlertController,
    private iab: InAppBrowser,
    private processes: ProcessesService,
    public popoverController: PopoverController,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private toastService: ToastService,
    private location: Location
  )
  {
    this.isEventEdited = false;
    this.loadedEvent = new Event();
    this.eventBody = { BodyType : "1", Text : ""};
    this.loadedEvent.Body = this.eventBody;
    this.activatedRoute.paramMap.subscribe(params =>{
      this.eventId = params['params'].eventId;
      if(params["params"].caller){
        this.caller = (params["params"].caller);
      }

      if(params["params"].isModal) {
        this.isModal = params["params"].isModal
      }

      if(params["params"].header) {
        this.header = params["params"].header
      }
    });

    /* this.activatedRoute.queryParams.subscribe(params => {
      if(params["eventId"]) {
        this.eventId = params["eventId"];
        console.log(params["eventId"]);
      }
    }); */

  }

  ngOnInit() {

    this.loadEvent();


    window.onresize = (event) => {
      // if not mobile remove all component
      if( window.innerWidth >= 1024) {
        this.modalController.dismiss(this.isEventEdited);
      }
    };

  }

  close(){

    this.modalController.dismiss(this.isEventEdited);
  }

  goBack() {

    if(this.isModal) {
      this.close()
    } else {
        this.activatedRoute.paramMap.subscribe(params => {
          if(params["params"].caller == 'expediente'){
            window.history.back();
          }
          else{
            this.router.navigate(['/home',params["params"].caller]);
          }
      });
    }

  }

  loadEvent() {
    const loader = this.toastService.loading();
    this.eventsService.getEvent(this.eventId).subscribe(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()]); */
      loader.remove()
    }, (error)=>{
      
      if(error.status == 0) {
        this.toastService.badRequest('Não é possível  vizualizar este evento no modo offline')
      } else {
        this.toastService.badRequest('Este evento já não existe na sua agenda')
      } 

      loader.remove()
      this.modalController.dismiss('Eevent not Foud');
      this.location.back();
    });
  }

  deleteEvent(){
    this.eventsService.deleteEvent(this.loadedEvent.EventId, 0).subscribe(async () =>
      {
        const alert = await this.alertController.create({
          cssClass: 'my-custom-class',
          header: 'Evento removido',
          buttons: ['OK']
        });

        setTimeout(()=>{
          alert.dismiss();
        }, 1500);
        this.goBack();
        this.toastService.successMessage('Evento apagado');
      });
  }


  async OpenDeleteEventModal() {
    
    const modal = await this.modalController.create({
      component: EliminateEventPage,
      componentProps: {
        eventId: this.loadedEvent.EventId,
        caller: this.caller,
      },
      cssClass: 'discart-expedient-modal',

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

      if(res){
        setTimeout(() => {
          /* this.loadEvent(); */
          this.loadEvent()
        }, 250);
        this.isEventEdited = true;
      }
    });

  }


  async editEventDetail() {

    const modal = await this.modalController.create({
      component: EditEventPage,
      componentProps: {
        eventId: this.loadedEvent.EventId,
        caller: this.caller,
      },
      cssClass: 'modal modal-desktop',

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

      if(res){
        setTimeout(() => {
          /* this.loadEvent(); */
          this.loadEvent()
        }, 250);
        this.isEventEdited = true;
      }
    });

  }

  async editEvent() {
    console.log(this.loadedEvent);

    let classs;
    if( window.innerWidth <= 800){
      classs = 'modal modal-desktop'
    } else  {
      classs = 'modal modal-desktop showAsideOptions'
    }

    const modal = await this.modalController.create({
      component: EditEventPage,
      componentProps:{
        event: this.loadedEvent,
        caller: this.caller,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then((res) => {
      console.log(res);

      if(res){
        setTimeout(() => {
          /* this.loadEvent(); */
          this.loadEvent()
        }, 250);
        this.isEventEdited = true;
      }
    });
  }

  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 = {
      serialNumber: doc.SourceId,
      taskStartDate: doc.CreateDate,
      isEvent: true,
      workflowInstanceDataFields: {
        FsId: doc.ApplicationId,
        FolderID: null,
        DocId: doc.SourceId,
        Subject: doc.SourceName
      },
    }

    const popover = await this.popoverController.create({
      component: OptsExpedientePage,
      cssClass: 'exp-options',
      componentProps: {
        fulltask: customTask,
        task: customTask
      },
      translucent: true
    });
    return await popover.present();
  }


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

}
