import { Component, OnInit, ViewChild } from '@angular/core';
import { AnimationController, ModalController, Platform } from '@ionic/angular';
import { SearchPage } from 'src/app/pages/search/search.page';
import { Router } from '@angular/router';
import { LoginUserRespose } from 'src/app/models/user.model';
import { ProfilePage } from 'src/app/modals/profile/profile.page';
import { StorageService } from '../../services/storage.service';
import { SessionStore } from 'src/app/store/session.service';
//import { NotificationsService } from '../../services/notifications.service';
import { environment } from 'src/environments/environment';
import { EventTrigger } from '../../services/eventTrigger.service';
import { ThemeService } from '../../services/theme.service';
import { interval } from 'rxjs';

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

  searchSubject: string = '';
  showSearch = false;
  loggeduser: LoginUserRespose;
  hideSearchBtn: boolean = false;
  notificationdata: any[] = [];
  DataArray: Array<object> = [];
  notificationLength: 0;
  SessionStore = SessionStore
  check: boolean;

  production = environment.production

  constructor(
    private router: Router,
    private modalController: ModalController,
    private animationController: AnimationController,
    private storageservice: StorageService,
    private platform: Platform,
    //private notificationsService: NotificationsService,
    private eventrigger: EventTrigger,
    public ThemeService: ThemeService
  ) {
    this.loggeduser = SessionStore.user;
    router.events.subscribe((val) => {
      this.showSearch = false;
      //this.modalController.dismiss();
    });
  }

  ngOnInit() {
    this.hideSearch();
    this.update()
    /* this.notificationLengthData();
    this.eventrigger.getObservable().subscribe(async (data) => {
      if (data.notification === "delete" || "recive") {
        await this.notificationLengthData();
        console.log('Current badge: ', this.notificationLength)
        console.log('Deleted notification', data.notification)
      }

    }) */
  }

  update() {
    setInterval(() => {
      this.notificationLengthData();
    }, 5000)

  }

  /*  UpdateNotificationCount() {
     this.notificationsService.registerCallback(
       'any',
       () => {
         setTimeout(()=>{
           this.notificationLengthData();
         }, 100)
       }
     )
   } */

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

      /*  var data = JSON.parse(value); */
      this.notificationLength = value.length;
      console.log('Timer badge count 1', this.notificationLength)
    })

    console.log('Timer badge count2', this.notificationLength)
  }

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

  locationPathname(): string {
    return window.location.pathname
  }

  async openSearch() {

    let classs, showSearchInput, type;
    if (window.innerWidth < 1366) {
      classs = 'modal modal-width-100'
      showSearchInput = true
    } else {
      classs = 'modal modal-desktop desktop-search'
      showSearchInput = false
    }



    if (window.location.pathname.startsWith('/home/agenda')) {
      type = "Agenda"
    } else if (window.location.pathname.startsWith('/home/gabinete-digital')) {
      type = "AccoesPresidenciais & ArquivoDespachoElect"

    } else if (window.location.pathname.startsWith('/home/publications')) {
      type = "AccoesPresidenciais"
    }

    const modal = await this.modalController.create({
      component: SearchPage,
      cssClass: classs,
      componentProps: {
        type: type,
        showSearchInput: showSearchInput,
        select: false
      }
    });
    return await modal.present();
  }

  changeRoute(path) {
    this.router.navigateByUrl(path)
  }


  async openProfile() {

    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: ProfilePage,
      cssClass: 'model profile-modal search-submodal',
      componentProps: {
      }
    });
    await modal.present();

    modal.onDidDismiss().then(() => {
      this.notificationLengthData()
    })

  }

  async dynamicSearch() {
    window['dynamicSearch'](this.searchSubject)
  }


  async closeSearch() {
    this.modalController.dismiss()
  }

  /**
  * @description set empty value to searchSubject
  */
  clearSearchInput() {
    this.searchSubject = "";
    window['dynamicSearch'](this.searchSubject)
  }

  async basicSearch() {
    window['searchTriger']()
  }

  profileLabel(text) {
    if (text == 'MDGPR') {
      return 'MD'
    } else if (text == 'PR') {
      return text
    } else {
      return 'UN'
    }
  }
}
