///<reference path="../../../../plugins/cordova-plugin-mfp/typings/worklight.d.ts" />
///<reference path="../../../../plugins/cordova-plugin-mfp-jsonstore/typings/jsonstore.d.ts" />
import { Component, OnInit, NgZone } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { AnimationController, ModalController,Platform } from '@ionic/angular';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AuthService } from 'src/app/services/auth.service';
import { LocalstoreService } from 'src/app/store/localstore.service';
import { EditProfilePage } from './edit-profile/edit-profile.page';
import { JsonStore } from '../../services/jsonStore.service';
import { StorageService } from '../../services/storage.service';
import { NotificationsService } from '../../services/notifications.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {

  loggeduser: LoginUserRespose;
  userLoginPreference = ''
  notificationdata: any[] = [];
  DataArray: Array<Object> = [];

  service: "agenda";
  typeagenda: "official";
  typeagenda2: "pessoal";
  pr: "100000014";
  md: "100000011";
  date:"60:20";
  location: "Gabinete";

  constructor(private modalController: ModalController,
    private authService: AuthService,
    private animationController: AnimationController,
    private router: Router,
    private localstoreService: LocalstoreService,
    private jsonstore: JsonStore,
    private storageservice: StorageService,
    private zone: NgZone,
    private notificationservice: NotificationsService,
    private platform: Platform,
  ) {

    this.loggeduser = authService.ValidatedUser;

    console.log(this.loggeduser.RoleDescription)

    this.checkState()
  }

  ngOnInit() {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      console.log('Notifications not supported')
    } else {
    this.getNotificationData();
    }

  }

  close() {
    this.modalController.dismiss();
  }

  notImplemented() { }

  async getNotificationData(){
    this.storageservice.get("Notifications").then((value) => {
      console.log("Init get store", value)

      var data = JSON.parse(value);
      console.log("Init store parse", data)
      data.forEach((element,i) => {
        console.log("ARaaAA", element)
        let notificationObject;
        if(element.payload){
          var payload = JSON.parse(element.payload)
          notificationObject = {
            index: i,
            alert: element.alert,
            Service: payload.Service,
            Object: payload.Object,
            IdObject: payload.IdObject,
            FolderId: payload.FolderId,
            desc: payload.desc,
            dateInit: this.getFormatedTime(payload.dateInit),
            dateEnd: this.getFormatedTime(payload.dateEnd),
            Location: payload.Location,
            TypeAgenda: payload.TypeAgenda,
            Role: payload.Role,
            Status: payload.Status
          }
        } else {
          notificationObject = {
            index: i,
            alert: element.alert,
            Service: element.Service,
            Object: element.Object,
            IdObject: element.IdObject,
            FolderId: element.FolderId,
            desc: element.desc,
            dateInit: element.dateInit,
            dateEnd: element.dateEnd,
            Location: element.Location,
            TypeAgenda: element.TypeAgenda,
            Role: element.Role,
            Status: element.Status
          }
        }
        

        this.DataArray.push(notificationObject)
      });
      this.notificationdata = this.DataArray
      console.log("Notificaaa", this.notificationdata)
    })
    console.log("Notificaaa", this.notificationdata)
    /* await new Promise(resolve => setTimeout(resolve, 1000));
    await this.getNotificationData(); */
    console.log('Timer badge count')
  }

  typeAgendaColor(service,typeagenda,role){
    if (service == "agenda" && typeagenda == "oficial" && role == "100000011"){
      document.body.style.setProperty(`--notificationtypeagenda`, "#ffb703");
    } else if( service == "agenda" && typeagenda == "pessoal" && role == "100000011"){
      document.body.style.setProperty(`--notificationtypeagenda`, "#ff0303");
    } else if (service == "agenda" && typeagenda == "oficial" && role == "100000014"){
      document.body.style.setProperty(`--notificationtypeagenda`, "#03d838");
    } else if (service == "agenda" && typeagenda == "oficial" && role == "100000014"){
      document.body.style.setProperty(`--notificationtypeagenda`, "#8b0ae0");
    }
  }

  getFormatedTime(dateString){
    var date = new Date(dateString);
    var hours = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
    var am_pm = date.getHours() >= 12 ? "pm" : "am";
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    let time = hours + ":" + minutes /* + " " + am_pm */;
    console.log('Formate',time)
    return time;
 }

  notificatinsRoutes = (index, Service, Object, IdObject, FolderId) => {

    if (Service === "agenda" && IdObject.length > 10) {
      console.log("Id Lenght",IdObject.length)
      this.zone.run(() => this.router.navigate(['/home/agenda', IdObject, 'agenda']));
    }
    else if (Service === "gabinete-digital" && Object === "expediente") {
      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente', IdObject, 'gabinete-digital']));
    }
    else if (Service === "agenda" && Object === "event-list") {
      //this.zone.run(() => this.router.navigate(['/home/gabinete-digital/event-list/approve-event',IdObject, 'agenda']));
      this.zone.run(() =>this.router.navigate(['/home/agenda/event-list/approve-event',IdObject, 'agenda']));
      
    } else if (Service === "gabinete-digital" && Object === "despachos") {

      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos', IdObject, 'gabinete-digital'], { replaceUrl: true }));
    }
    else if (Service === "gabinete-digital" && Object === "parecer") {

      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', IdObject, 'gabinete-digital']));
    }
    else if (Service === "gabinete-digital" && Object === "deferimento") {

      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', IdObject, 'gabinete-digital']));
    }
    else if (Service === "gabinete-digital" && Object === "despachos-pr") {

      this.zone.run(() =>this.router.navigate(['/home/gabinete-digital/despachos-pr',IdObject,'gabinete-digital']));
    }
    else if (Service === "accoes" && Object === "accao") {
      this.zone.run(() => this.router.navigate(['/home/publications', IdObject]));
    }
    else if (Service === "accoes" && Object === "publicacao") {
      this.zone.run(() => this.router.navigate(['/home/publications/view-publications', FolderId, IdObject]));
    }
    else if (Service === "gabinete-digital" && Object === "diplomas") {
      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas', IdObject, 'gabinete-digital']));
    }
    else if (Service === "gabinete-digital" && Object === "diplomas-assinar") {
      
      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas-assinar',IdObject,'gabinete-digital']));
    }
    else if (Service === "gabinete-digital" && Object === "expedientes-pr") {
      this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expedientes-pr', IdObject, 'gabinete-digital']));
    }

    this.notificationservice.tempClearArray();
    this.deleteNotification(index);


  }

  deleteNotification(index){
    console.log("Delete notification first stata", this.notificationdata)
    this.notificationdata = this.notificationdata.filter(item=>item.index !=index );
    
    this.storageservice.store("Notifications",JSON.stringify(this.notificationdata)).then(() =>{
      this.storageservice.get("Notifications").then((value) =>{
        console.log("notfication state", value, )
      });
    });
    console.log("Delete notification last stata", this.notificationdata)

  }

  logout() {
    window.localStorage.clear();

    setTimeout(() => {
      this.router.navigateByUrl('/', { replaceUrl: true });
    }, 100)

  }

  checkState() {

    let userData = this.localstoreService.get('UserData', {})

    if (userData.hasOwnProperty('loginPreference')) {
      this.userLoginPreference = userData.loginPreference
    } else {
      this.userLoginPreference = ''
    }

  }

  async editProfile() {

    const enterAnimation = (baseEl: any) => {
      const backdropAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('ion-backdrop')!)
        .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

      const wrapperAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('.modal-wrapper')!)
        .keyframes([
          { offset: 0, opacity: '1', right: '-100%' },
          { offset: 1, opacity: '1', right: '0px' }
        ]);

      return this.animationController.create()
        .addElement(baseEl)
        .easing('ease-out')
        .duration(500)
        .addAnimation([backdropAnimation, wrapperAnimation]);
    }

    const leaveAnimation = (baseEl: any) => {
      return enterAnimation(baseEl).direction('reverse');
    }


    const modal = await this.modalController.create({
      enterAnimation,
      leaveAnimation,
      component: EditProfilePage,
      cssClass: 'model profile-modal',
      componentProps: {
      }
    });
    return await modal.present();
  }

}
