import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { UserForm } from 'src/app/models/user.model';
import { ToastService } from 'src/app/services/toast.service';
import { environment } from 'src/environments/environment';
import { AlertController } from '@ionic/angular';
import { NotificationsService } from 'src/app/services/notifications.service';
import { SessionStore } from 'src/app/store/session.service';
import { ThemeService } from 'src/app/services/theme.service';

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

  username: string = environment.defaultuser;
  password: string = environment.defaultuserpwd;
  userattempt: UserForm;
  code = []
  setPin = false
  SessionStore = SessionStore
  enterWithPassword = false

  constructor(
    private notificatinsservice: NotificationsService,
    private router: Router,
    private authService: AuthService,
    private toastService: ToastService,
    public alertController: AlertController,
    public ThemeService: ThemeService,
  ) {}

  loop = false

  ngOnInit() {
    

    // window.addEventListener('resize', (event) => {
    //   if(this.router.url != '/login') return false
      
    //   if(this.loop == false) {
    //     this.loop = true
    //     this.runloop()
    //   }

    // }, true);

  }

  runloop() {
    // const containerHeight = 651

    // let circleHeight = document.querySelector('.circle')['offsetHeight']
    // let circleWidth = document.querySelector('.circle')['offsetWidth'] 
    // console.log(window.innerHeight, ' < ', containerHeight)

    // console.log(circleHeight)

    // document.querySelectorAll('.circle').forEach(e=>{
    //   e['style']['height'] = (circleHeight -1 )+'px'
    //   e['style']['width'] = (circleWidth -1 )+'px'
    // })

    
    // if( window.innerHeight< containerHeight) {
    //   setTimeout(()=>{
    //     this.runloop()
    //   }, 100)
    // } else {
    //   this.loop = false
    // }

  }

  async presentAlert(message: string) {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: 'Mensagem do sistema',
      message: message,
      buttons: ['OK']
    });

    await alert.present();
  }


  //Function to validade the login inputs
  validateUsername() {
    return (
      this.username.trim().length > 0
    );
  }

  validatePassword() {
    return (
      this.password.trim().length > 0
    );
  }

  async Login() {

    if (this.validateUsername()) {
      if(this.validatePassword()) {

        this.userattempt = {
          username: this.username,
          password: this.password,
          domainName: environment.domain,
          BasicAuthKey: ""
        }
        let attempt = await this.authService.login(this.userattempt, {saveSession: false})

        if (attempt) {
          
          // if current attemp is equal to the current user
          if (attempt.UserId == SessionStore.user.UserId) {
            await this.authService.SetSession(attempt, this.userattempt);
            this.authService.loginChat(this.userattempt);
            this.getToken();
            SessionStore.setInativity(true)
            
            this.goback()
          } else {
            SessionStore.delete()
            window.localStorage.clear();
            await this.authService.SetSession(attempt, this.userattempt);
          }

          this.enterWithPassword = false
        }
      }
      else {
        this.toastService._badRequest('Por favor, insira a sua palavra-passe');
      }
    }
    else {
      this.toastService._badRequest('Por favor, insira o seu nome de utilizador');
    }
  }

  getToken() {
    this.notificatinsservice.requestPermissions();
    this.notificatinsservice.registrationError();
    this.notificatinsservice.getAndpostToken(this.username);
  }

  setCode(code: string) {

    if(this.code.length < 4) {
      this.code.push(code)
    }

    if(this.code.length == 4) {

      if(!SessionStore.hasPin) {
        // console.log('storePin')
        this.storePin()
      } else {
        // console.log('pinLogin')
        this.pinLogin()
      }
    }
  }

  clearCode() {
    this.code =[]
  }

  pinLogin() {

    const code = this.code.join('')

    if( SessionStore.validatePin(code)) {
      
      SessionStore.setInativity(true)
      this.goback()
      
      setTimeout(()=>{
        this.clearCode()
      }, 1000)

    } else {
      this.toastService._badRequest('Pin incorreto')
      this.code = []
    }

  }

  goback() {
    const pathName = this.SessionStore.user.UrlBeforeInactivity
    if(pathName) {
      this.router.navigate([pathName],{replaceUrl: true});
    } else {
      this.router.navigate(['/home/events'], {replaceUrl: true});
    }
    
  }

  storePin() {

    const code = this.code.join('')

    SessionStore.setPin(code)

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

  }

  enterWithPasswordButton() {
    this.enterWithPassword = true
  }

}
