import { Component, OnInit, LOCALE_ID, EventEmitter, Output, Renderer2, ElementRef } from '@angular/core';

import { Event } from '../../models/event.model';
import { EventsService } from 'src/app/services/events.service';
import { NavigationExtras, Router } from '@angular/router';
import { ActivatedRoute, NavigationEnd } from '@angular/router';
import { AlertService } from 'src/app/services/alert.service';
import { AuthService } from 'src/app/services/auth.service';
import { StorageService } from 'src/app/services/storage.service';
import { ModalController, Platform } from '@ionic/angular';
import { EventDetailPage } from './event-detail/event-detail.page';
import { ProcessesService } from '../../services/processes.service';
import { DailyWorkTask } from '../../models/dailyworktask.model';
import { LoginUserRespose } from 'src/app/models/user.model';
import { ToDayEventStorage } from 'src/app/store/to-day-event-storage.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import { ExpedienteTaskPipe } from 'src/app/pipes/expediente-task.pipe';
import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service';
import { SqliteService } from 'src/app/services/sqlite.service';
import { NetworkConnectionService } from 'src/app/services/network-connection.service'
import { BackgroundService } from 'src/app/services/background.service';
import { momentG } from 'src/plugin/momentG';
import { ThemeService } from 'src/app/services/theme.service'
@Component({
  selector: 'app-events',
  templateUrl: './events.page.html',
  styleUrls: ['./events.page.scss'],
})
export class EventsPage implements OnInit {
  /* Get current system date */
  today = new Date();

  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"];

  customDate = this.days[this.today.getDay()] + ", " + this.today.getDate() + " de " + (this.months[this.today.getMonth()]);

  /* Setting appropriate greeting according to the time */
  grettings = ["Bom dia", "Boa tarde", "Boa noite"];
  greetting = '';

  timeDate = this.today.getHours() + ":" + this.today.getMinutes();
  /* Set segment variable */
  segment: string;
  public profile: string;
  currentEvent: any;

  eventsList: Event[];
  maxSubjectLength = 30;
  officialeventsList: Event[];
  personaleventsList: Event[];

  prEventList: Event[];
  mdEventList: Event[];

  combinedEvents: Event[];

  customText = false;
  totalEvent = 0;
  currentHoursMinutes: Date | string;

  showLoader: boolean;

  taskslist: DailyWorkTask[] = [];
  expedientList: any;
  hideSearchBtn: boolean = false;

  // shared data
  toDayEventStorage = ToDayEventStorage
  expedienteGdStore = ExpedienteGdStore

  listToPresent = [];
  listToPresentexpediente = []

  expedienteTaskPipe = new ExpedienteTaskPipe()

  @Output() openExpedientListPage: EventEmitter<any> = new EventEmitter<any>();

  loggeduser: LoginUserRespose;

  /* existingScreenOrientation: string; */

  constructor(
    private eventService: EventsService,
    private router: Router,
    private storageService: StorageService,
    public activatedRoute: ActivatedRoute,
    private alertController: AlertService,
    private authService: AuthService,
    private processes: ProcessesService,
    /* private gabineteService: GabineteDigitalPage, */
    private modalController: ModalController,
    private screenOrientation: ScreenOrientation,
    public platform: Platform,
    private sqliteservice: SqliteService,
    private networkconnection: NetworkConnectionService,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService
  ) {
  /*   this.existingScreenOrientation = this.screenOrientation.type;
    console.log(this.existingScreenOrientation); */

    this.loggeduser = authService.ValidatedUser;

    this.prEventList = null;

    this.platform.resize.subscribe(async () => {
      //console.log('Resize event detected');
      // console.log('Resize event detected');

    });

    window['zipPhoneCallback'] = function (zipphone) {
      var frame = document.getElementById('home-iframe');
      if(frame) {
        frame['contentWindow']['postMessage']({call:'cookies', value: { cookies: {} }});
      }
    }

  }

  ngOnInit() {

    this.segment = "Combinada";
    this.profile = "mdgpr";

    this.showGreeting();

    this.router.events.forEach((event) => {
      if (event instanceof NavigationEnd && event.url == '/home/events') {
        this.RefreshEvents();
        setTimeout(() => {
          this.LoadList();
        }, 1500)
      }
    });
    this.hideSearch();

    this.backgroundservice.registerBackService('Online', () => {
      this.showGreeting();
      this.RefreshEvents();
      this.LoadList();
      this.hideSearch();
    });

    //this.getEventsFromLocalDb();

    //this.checkScreenOrientation();

  }

  hideSearch() {
    if (this.router.url == '/home/events') {
      this.hideSearchBtn = true;
    }
  }

  doRefresh(event) {
    this.RefreshEvents();
    this.LoadList();
    event.target.complete();
  }

  onSegmentChange() {
    this.RefreshEvents();
  }

  // Lock to portrait
/*   lockToPortrait() {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
    console.log('set');
  } */

  // Lock to landscape
  /* lockToLandscape() {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
  } */

  // Unlock screen orientation
  /* unlockScreenOrientation() {
    this.screenOrientation.unlock();
  } */

 /*  checkScreenOrientation() {
    if (window.innerWidth < 701) {
      this.lockToPortrait();
      console.log('was here');

    }
    else {
      this.unlockScreenOrientation();
    }
  } */

  async RefreshEvents() {
    this.currentEvent = "";
    this.showLoader = true;

    let date = new Date();
    let month = date.getMonth() + 1;
    //date.setMonth(date.getMonth() + 1);
    let start = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    let end = date.getFullYear() + "-" + month + "-" + date.getDate() + " 23:59:59";

    console.log('Data start yahaya', start)
    console.log('Data end yahaya', end)

    if (this.loggeduser.Profile == 'MDGPR') {

      let mdOficialEvents = await this.eventService.getAllMdOficialEvents(start, end).toPromise();
      let mdPessoalEvents = await this.eventService.getAllMdPessoalEvents(start, end).toPromise();

      const list = mdOficialEvents.concat(mdPessoalEvents);
     
      this.addEventToDb(list);
      this.listToPresent = list

      if (list.length > 0) {
        this.currentEvent = list[0].Subject;
        this.currentHoursMinutes = list[0].StartDate;
      }

      this.totalEvent = list.length;
      this.showLoader = false;

    }
    else if (this.loggeduser.Profile == 'PR') {

      let prOficialEvents = await this.eventService.getAllPrOficialEvents(start, end).toPromise();
      let prPessoalEvents = await this.eventService.getAllPrPessoalEvents(start, end).toPromise();

      const list = prOficialEvents.concat(prPessoalEvents);
      console.log("getAllPrOficialPessoalEvents", list)
      this.addEventToDb(list);
      if (list.length > 0) {
        this.currentEvent = list[0].Subject;
        this.currentHoursMinutes = list[0].StartDate;
      }

      this.listToPresent = list;
      this.totalEvent = list.length;
      this.showLoader = false;

    }


    /* switch (this.segment)
    {
      case "Combinada":
        if(this.loggeduser.Profile == 'MDGPR'){

          let mdOficialEvents = await this.eventService.getAllMdOficialEvents(start, end).toPromise();
          let mdPessoalEvents = await this.eventService.getAllMdPessoalEvents(start, end).toPromise();

            this.eventsList = mdOficialEvents.concat(mdPessoalEvents);

            if(this.eventsList.length > 0){
              this.currentEvent = this.eventsList[0].Subject;
              this.currentHoursMinutes = this.eventsList[0].StartDate;
            }

            this.totalEvent = this.eventsList.length;
            this.showLoader = false;

        }
        else{

          let prOficialEvents=  await this.eventService.getAllPrOficialEvents(start, end).toPromise();
          let prPessoalEvents=  await this.eventService.getAllPrPessoalEvents(start, end).toPromise();
            this.eventsList = prOficialEvents.concat(prPessoalEvents);
            console.log(this.eventsList);
            console.log(this.eventsList);

            if(this.eventsList.length > 0){
              this.currentEvent = this.eventsList[0].Subject;
              this.currentHoursMinutes = this.eventsList[0].StartDate;
            }

            this.totalEvent = this.eventsList.length;
            this.showLoader = false;

        }

        break;
      case "Pessoal":
        if(this.loggeduser.Profile == 'MDGPR'){
         this.eventService.getAllMdPessoalEvents(start, end).subscribe(res => {
          this.personaleventsList = res.filter(data => data.CalendarName == "Pessoal");
          this.showLoader = false;
         });
        }
        else{
          this.eventService.getAllPrPessoalEvents(start, end).subscribe(res => {
            this.personaleventsList = res.filter(data => data.CalendarName == "Pessoal");
            this.showLoader = false;
           });
        }

        break;
      case "Oficial":
        if(this.loggeduser.Profile == 'MDGPR'){
           this.eventService.getAllMdOficialEvents(start, end).subscribe(res => {
            this.officialeventsList = res.filter(data => data.CalendarName == "Oficial");;
            this.showLoader = false;
           });
        }
        else{
          this.eventService.getAllPrOficialEvents(start, end).subscribe(res => {
            this.officialeventsList = res.filter(data => data.CalendarName == "Oficial");;
            this.showLoader = false;
           });
        }
        break;
    } */
  }

  addEventToDb(list) {

    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      if (list.length > 0) {
        list.forEach(element => {
          this.sqliteservice.addEvent(element)

          this.sqliteservice.getAllEvents().then((event: any[]) => {
            let todayEvents = new Array()
            event.forEach((element) => {
              let eventObject = {
                AppointmentState: element.AppointmentState,
                Attachments: element.Attachments,
                Attendees: element.Attendees,
                CalendarId: element.CalendarId,
                CalendarName: element.CalendarName,
                Category: element.Category,
                EndDate: element.EndDate,
                EventId: element.EventId,
                EventRecurrence: element.EventRecurrence,
                EventType: element.EventType,
                HasAttachments: element.HasAttachments,
                HumanDate: element.HumanDate,
                IsAllDayEvent: element.IsAllDayEvent,
                IsMeeting: element.IsMeeting,
                IsRecurring: element.IsRecurring,
                Location: element.Location,
                Organizer: element.Organizer,
                Profile: element.Profile,
                StartDate: element.StartDate,
                Subject: element.Subject
              }
                todayEvents.push(eventObject);
            })
            console.log('JIFJSOSDJSDONS',todayEvents)
          })
        });
      }
    }
  }

  addProcessToDb(list) {

    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      if (list.length > 0) {
        list.forEach(element => {
          this.sqliteservice.addProcess(element)
        });
      }
    }
  }

  getEventsFromLocalDb() {

    let date = new Date();
    let month = date.getMonth() + 1;
    //date.setMonth(date.getMonth() + 1);
    let dateToday = date.getFullYear() + "-" + month + "-" + date.getDate();
    console.log('dateeeeee', dateToday)
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {

    } else {
      this.sqliteservice.getAllEvents().then((event: any[]) => {
        let todayEvents = new Array()
        event.forEach((element) => {
          let eventObject = {
            AppointmentState: element.AppointmentState,
            Attachments: element.Attachments,
            Attendees: element.Attendees,
            CalendarId: element.CalendarId,
            CalendarName: element.CalendarName,
            Category: element.Category,
            EndDate: element.EndDate,
            EventId: element.EventId,
            EventRecurrence: element.EventRecurrence,
            EventType: element.EventType,
            HasAttachments: element.HasAttachments,
            HumanDate: element.HumanDate,
            IsAllDayEvent: element.IsAllDayEvent,
            IsMeeting: element.IsMeeting,
            IsRecurring: element.IsRecurring,
            Location: element.Location,
            Organizer: element.Organizer,
            Profile: element.Profile,
            StartDate: element.StartDate,
            Subject: element.Subject
          }
          let starteDate = momentG(new Date(element.StartDate), 'yyyy-MM-dd');
          console.log('startTOdayyy', starteDate)
          if (dateToday == starteDate) {
            todayEvents.push(eventObject);
          }
        })
        this.listToPresent = todayEvents
        this.totalEvent = this.listToPresent.length
        this.currentEvent = this.listToPresent[0].Subject
        this.currentHoursMinutes = this.listToPresent[0].StartDate
        console.log("All events from local,", event)
      })

      this.sqliteservice.getprocessByworkflow("Expediente").then((process: any[]) => {

        console.log('OFOFOFOOF', process)

        if (process.length > 0 || process != undefined) {

          var expedientlist: any = new Array();
          process.forEach((element) => {
            if(JSON.parse(element.workflowInstanceDataFields).TaskMessage || JSON.parse(element.workflowInstanceDataFields).Note) {

              let task = {
                activityInstanceName: element.activityInstanceName,
                deadline: null,
                serialNumber: element.serialNumber,
                taskStartDate: element.taskStartDate,
                totalDocuments: element.totalDocuments,
                workflowDisplayName: element.workflowDisplayName,
                workflowInstanceDataFields: JSON.parse(element.workflowInstanceDataFields)
              }
              expedientlist.push(task);

            }
          })

          console.log('OFOFOFOOF22222', expedientlist)
          const ExpedienteTask = expedientlist.map(e => this.expedienteTaskPipe.transform(e))
          this.listToPresentexpediente = ExpedienteTask;

        }

        this.showLoader = false;
      })
    }
    // });
  }



  showGreeting() {
    if (this.today.getHours() >= 6 && this.today.getHours() < 12) {
      this.greetting = this.grettings[0];
    }
    else if (this.today.getHours() >= 12 && this.today.getHours() < 18) {
      this.greetting = this.grettings[1];
    }
    else /* if(this.today.getHours() < 6 && this.today.getHours() >= 18) */ {
      this.greetting = this.grettings[2];
    }
  }

  gotTo() {
    this.router.navigate(['/home/events']);
  }

  changeProfile() {
    if (this.profile == "mdgpr") {
      console.log('pr');
      this.profile = "pr";
      this.RefreshEvents();
    }
    else {
      console.log('mdgpr');
      this.profile = "mdgpr";
      this.RefreshEvents();
    }
  }

  logout() {
    this.authService.ValidatedUser.BasicAuthKey = "";
    this.router.navigate(['/home/login']);
  }

  async openEventDetail1(id: any) {
    console.log(id);

    const modal = await this.modalController.create({
      component: EventDetailPage,
      componentProps: {
        eventId: id,
      },
      cssClass: 'event-detail',
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss();

  }

  LoadList() {
    this.processes.GetTaskListExpediente(false).subscribe(result => {
      console.log("Expediente", result);
      this.addProcessToDb(result);

      const ExpedienteTask = result.map(e => this.expedienteTaskPipe.transform(e))

      console.log("Expediente 2", ExpedienteTask);

      this.listToPresentexpediente = ExpedienteTask;
    }, ((error) => {
      console.log('Getlist error', error)
      this.getEventsFromLocalDb();
    }));
  }

  sortArrayISODate(myArray: any) {
    return myArray.sort(function (a, b) {
      return (a.CreateDate < b.CreateDate) ? -1 : ((a.CreateDate > b.CreateDate) ? 1 : 0);
    });
  }

  goToEvent(eventId: any) {
    this.router.navigate(['/home/events', eventId, 'events']);
  }

  goToExpediente(SerialNumber: any) {
    this.router.navigate(['/home/events/expediente', SerialNumber, 'events']);
    /* if (this.loggeduser.Profile == 'MDGPR') {
      this.router.navigate(['/home/events/expediente', SerialNumber, 'events']);
    }
    else if (this.loggeduser.Profile == 'PR') {
      this.router.navigate(['/home/events/expedientes-pr', SerialNumber, 'events']);
    } */
  }

  viewExpedientListPage() {
    if (this.loggeduser.Profile == 'MDGPR') {
      if (window.innerWidth < 701) {
        this.router.navigate(['/home/gabinete-digital/expediente']);
      }
      else {
        let navigationExtras: NavigationExtras = { queryParams: { "expedientes": true, } };
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    }
    else if (this.loggeduser.Profile == 'PR') {
      if (window.innerWidth < 701) {
        this.router.navigate(['/home/gabinete-digital/expedientes-pr']);
      }
      else {
        let navigationExtras: NavigationExtras = { queryParams: { "expedientes-pr": true, } };
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    }
  }



}



