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

@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

  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,
    ) {
      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');

      });

    }

  ngOnInit() {

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

    this.showGreeting();

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

    //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();
    date.setMonth(date.getMonth() + 1);
    let start = date.getFullYear()+"-"+ date.getMonth()+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+ ":"+date.getSeconds();
    let end = date.getFullYear()+"-"+ date.getMonth()+"-"+date.getDate()+" 23:59:59";


    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.toDayEventStorage.reset(list)

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

      this.totalEvent = this.toDayEventStorage.eventsList.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);

      this.toDayEventStorage.reset(list)

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

      this.totalEvent = this.toDayEventStorage.eventsList.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;
    } */
  }

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

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

      this.expedienteGdStore.reset(ExpedienteTask)
    });
  }

  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 < 801){
        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 < 801){
        this.router.navigate(['/home/gabinete-digital/expedientes-pr']);
      }
      else{
        let navigationExtras: NavigationExtras = { queryParams: {"expedientes-pr": true,} };
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    }
  }


}

