import { Component, OnInit } from '@angular/core';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { ModalController } from '@ionic/angular';
import { ApproveEventModalPage } from './approve-event-modal/approve-event-modal.page';
import { NavigationStart, Router } from '@angular/router';
import { EventoAprovacaoStore } from 'src/app/store/eventoaprovacao-store.service';
import { Location } from '@angular/common';

import { SqliteService } from '../../../services/sqlite.service';
import { BackgroundService } from '../../../services/background.service';
import { Platform } from '@ionic/angular';
import { SortService } from 'src/app/services/functions/sort.service';
import { ThemeService } from 'src/app/services/theme.service'
import { RouteService } from 'src/app/services/route.service';

@Component({
  selector: 'app-event-list',
  templateUrl: './event-list.page.html',
  styleUrls: ['./event-list.page.scss'],
})
export class EventListPage implements OnInit {
  // [desktop] event list to approve

  profile: string;
  segment: string;
  showLoader: boolean;
  eventsPRList: any = []
  eventsMDGPRList: any = []
  eventPerson: EventPerson;
  eventBody: EventBody;
  categories: string[];
  serialnumber: string;

  skeletonLoader = true
  eventaprovacaostore = EventoAprovacaoStore;

  constructor(
    private processes: ProcessesService,
    private modalController: ModalController,
    private router: Router,
    private location: Location,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private sortService: SortService,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService,
    private RouteService: RouteService
  ) { }

  ngOnInit() {

    this.segment = 'MDGPR';

    const location = window.location
    const pathname = location.pathname + location.search

    this.LoadToApproveEvents()

    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart && event.url.startsWith(pathname)) {
        if (window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/gabinete-digital')) {
          this.refreshing()
        } else {
          this.LoadToApproveEvents()
        }
      }
    });

    this.backgroundservice.registerBackService('Online', () => {
      this.LoadToApproveEvents();
    });

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

  }

  getEventToAproveFromDB() {

    this.platform.ready().then(() => {

      this.sqliteservice.getListOfEventAprove('Agenda Oficial MDGPR', 'Agenda Pessoal MDGPR').then((event: any[]) => {

        this.eventsMDGPRList = this.sortService.sortDate(this.transformaDataDB(event), 'taskStartDate')
        //this.eventsMDGPRList = this.eventsMDGPRList.filter(element => element.interveners != null)
        console.log('MD event to aprove', this.eventsMDGPRList)

      })

      this.sqliteservice.getListOfEventAprove('Agenda Oficial PR', 'Agenda Pessoal PR').then((event: any[]) => {
        this.eventsPRList = this.sortService.sortDate(this.transformaDataDB(event), 'taskStartDate')
        console.log('PR event to aprove', this.eventsPRList)

      })
    })
    console.log('Offlineee')
  }

  transformaDataDB(events) {
    let MdEventsArray = [];
    for (let i of events) {
      let eventMD = {
        Documents: i.Documents,
        actions: i.actions,
        activityInstanceName: i.activityInstanceName,
        formURL: i.formURL,
        interveners: i.interveners,
        originator: i.originator,
        serialNumber: i.serialNumber,
        taskStartDate: i.taskStartDate,
        totalDocuments: i.totalDocuments,
        workflowDisplayName: i.workflowDisplayName,
        workflowID: i.workflowID,
        workflowInstanceDataFields: JSON.parse(i.workflowInstanceDataFields),
        workflowInstanceFolio: i.workflowInstanceFolio,
        workflowInstanceID: i.workflowInstanceID,
        workflowName: i.workflowName,
      }

      MdEventsArray.push(eventMD);
    }
    return MdEventsArray;
  }

  segmentChanged(ev: any) {
    this.LoadToApproveEvents();
  }

  async LoadToApproveEvents() {
    this.processes.GetTasksList('Agenda Oficial MDGPR', false).subscribe(async res => {
      this.showLoader = true;
      this.skeletonLoader = true

      console.log(this.segment);
      if (this.segment == 'MDGPR') {
        let mdEventsOficial = await this.processes.GetTasksList('Agenda Oficial MDGPR', false).toPromise();
        let mdEventsPessoal = await this.processes.GetTasksList('Agenda Pessoal MDGPR', false).toPromise();
        this.eventsMDGPRList = mdEventsOficial.concat(mdEventsPessoal);
        this.eventsMDGPRList = this.sortService.sortDate(this.eventsMDGPRList, 'taskStartDate')
        console.log('MD EVENT TO APROVE ONLINE',this.eventsMDGPRList)
        this.eventaprovacaostore.resetmd(this.sortService.sortArrayByDate(this.eventsMDGPRList).reverse());
      }
      else if (this.segment == 'PR') {
        let prEventsOficial = await this.processes.GetTasksList('Agenda Oficial PR', false).toPromise();
        let prEventsPessoal = await this.processes.GetTasksList('Agenda Pessoal PR', false).toPromise();
        this.eventsPRList = prEventsOficial.concat(prEventsPessoal);
        this.eventsPRList = this.sortService.sortDate(this.eventsPRList, 'taskStartDate')
        console.log('PR EVENT TO APROVE ONLINE',this.eventsPRList)
        this.eventaprovacaostore.resetpr(this.sortService.sortArrayByDate(this.eventsPRList).reverse());
      }
      this.showLoader = false;
      this.skeletonLoader = false

    }, (error) => {
      this.getEventToAproveFromDB();
    })
  }

  async openApproveModal(eventSerialNumber, event) {
    const modal = await this.modalController.create({
      component: ApproveEventModalPage,
      componentProps: {
        serialNumber: eventSerialNumber,
      },
      cssClass: 'event-list cal-modal  modal modal-desktop',
      backdropDismiss: false
    });
    await modal.present();
  }

  goToEventToApproveDetail(serialNumber: string) {
    console.log(serialNumber);

    /* let navigationExtras: NavigationExtras = {
      queryParams: {
        "serialNumber": serialNumber,
      }
    }; */

    if (this.router.url == '/home/agenda/event-list') {
      this.router.navigate(['/home/agenda/event-list/approve-event', serialNumber, 'agenda'])
    }
    else if (this.router.url == '/home/gabinete-digital/event-list') {
      this.router.navigate(['/home/gabinete-digital/event-list/approve-event', serialNumber, 'gabinete-digital'])
    }

    //this.router.navigate(['/home/gabinete-digital/event-list/approve-event'], navigationExtras)
  }

  refreshing() {
    setTimeout(() => {
      this.LoadToApproveEvents();
    }, 1000);
  }

  doRefresh(event) {

    setTimeout(() => {
      this.LoadToApproveEvents();
      event.target.complete();
    }, 1000);
  }

  close() {
    this.modalController.dismiss(null);
  }
  goBack() {
    // if(this.router.url == '/home/agenda/event-list') {
    //   this.router.navigate(['/home/agenda']);
    // }
    // else if(this.router.url == '/home/gabinete-digital/event-list'){
    //   this.router.navigate(['/home/gabinete-digital']);
    // }

    this.RouteService.goBack()
  }


}
