import { Component, OnInit } from '@angular/core';
import { AlertController, ModalController, PopoverController, Platform, NavParams } 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 { 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'
import { SqliteService } from 'src/app/services/sqlite.service';
import { ExpedientTaskModalPageNavParamsTask } from 'src/app/models/ExpedientTaskModalPage';
import { DocumentSetUpMeetingPage } from 'src/app/modals/document-set-up-meeting/document-set-up-meeting.page';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { BackgroundService } from 'src/app/services/background.service';
import { StorageService } from 'src/app/services/storage.service';
import { ThemeService } from 'src/app/services/theme.service'
import { Event } from '../../models/event.model';
import { EditEventPage } from 'src/app/pages/agenda/edit-event/edit-event.page';
import { ExpedientTaskModalPage } from 'src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page';
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: 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
  task: ExpedientTaskModalPageNavParamsTask;
  LoadedDocument: any = null;

  constructor(
    private modalController: ModalController,
     private navParams: NavParams,
    private eventsService: EventsService,
    public alertController: AlertController,
    private iab: InAppBrowser,
    private processes: ProcessesService,
    public popoverController: PopoverController,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private toastService: ToastService,
    private RouteService: RouteService,
    public platform: Platform,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    private storage: StorageService,
    public ThemeService: ThemeService
  ) {
    this.eventId = this.navParams.get('eventId');
    this.isEventEdited = false;
    this.loadedEvent = new Event();
    this.eventBody = { BodyType: "1", Text: "" };
    this.loadedEvent.Body = this.eventBody;

  }

  ngOnInit() {
    this.loadEvent();

    this.backgroundservice.registerBackService('Online', () => {
      this.storage.get('eventEdit').then((req) => {
        JSON.parse(req).forEach(element => {
          this.eventsService.editEvent(element, 2, 3).subscribe((res) => {
            this.storage.remove('eventEdit')
            console.log('eventEdit synchnize', res)
          })
        });
      })
      this.storage.get('eventDelete').then((req) => {
        JSON.parse(req).forEach(element => {
          this.eventsService.editEvent(element, 2, 3).subscribe((res) => {
            this.storage.remove('eventDelete')
            console.log('eventEdit synchnize', res)
          })
        });
      })
      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() {
    this.close();
  }

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

  loadEvent() {
    const loader = this.toastService.loading();
    this.eventsService.getEvent(this.eventId).subscribe(res => {
      this.loadedEvent = res;
      this.addEventToDb(res);
      console.log('Loaded one event', 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) => {

      console.log('errorstatus ss',error.status)

      if (error.status === 0) {
        this.getFromDb();
      } else {
        this.toastService.badRequest('Este evento já não existe na sua agenda')
        loader.remove()
        this.modalController.dismiss('Eevent not Foud');
        this.RouteService.goBack();
      }
      loader.remove()
    });
  }

  deleteEvent() {

    const loader = this.toastService.loading()

    this.eventsService.deleteEvent(this.loadedEvent.EventId, 0, this.loadedEvent.CalendarName).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');
    }, () => { },
      () => {
        loader.remove();
      });

      loader.remove();
  }


  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;
      }
    });
  }

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

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

  }


  addEventToDb(data) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      let event = {
        Attendees: JSON.stringify(data.Attendees) || JSON.stringify(''),
        Body: JSON.stringify(data.Body) || JSON.stringify(''),
        CalendarId: data.CalendarId,
        CalendarName: data.CalendarName,
        Category: data.Category,
        EndDate: data.EndDate,
        EventId: data.EventId,
        EventRecurrence: JSON.stringify(data.EventRecurrence) || JSON.stringify(''),
        EventType: data.EventType,
        HasAttachments: data.HasAttachments,
        IsAllDayEvent: data.IsAllDayEvent,
        IsMeeting: data.IsMeeting,
        IsRecurring: data.IsRecurring,
        Location: data.Location,
        Organizer: JSON.stringify(data.Organizer) || JSON.stringify(''),
        StartDate: data.StartDate,
        Subject: data.Subject,
        TimeZone: data.TimeZone
      }

      this.sqliteservice.updateEvent(event);
    }
  }


  getFromDb() {
    const loader = this.toastService.loading();
    this.sqliteservice.getEventById(this.eventId).then((event) => {
      let arrayevent = [];
      console.log('EVENT ATTENDEES',event[0].Attendees)
      let elemet = {
        Attendees: (typeof JSON.parse(event[0].Attendees) === 'undefined') ? "" : JSON.parse(event[0].Attendees),
        Body: JSON.parse(event[0].Body) || "",
        CalendarId: event[0].CalendarId,
        CalendarName: event[0].CalendarName,
        Category: event[0].Category,
        EndDate: event[0].EndDate,
        EventId: event[0].EventId,
        EventRecurrence: JSON.parse(event[0].EventRecurrence) || "",
        EventType: event[0].EventType,
        HasAttachments: event[0].HasAttachments,
        IsAllDayEvent: event[0].IsAllDayEvent,
        IsMeeting: event[0].IsMeeting,
        IsRecurring: event[0].IsRecurring,
        Location: event[0].Location,
        Organizer: JSON.parse(event[0].Organizer) || "",
        StartDate: event[0].StartDate,
        Subject: event[0].Subject,
        TimeZone: event[0].TimeZone
      }
      arrayevent.push(elemet);
      this.loadedEvent = arrayevent[0];
      console.log("Event ditails local,", elemet)
    })
    loader.remove()
  }
}
