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 crypto  from  'crypto-js'
import { LocalstoreService } from 'src/app/store/localstore.service';
import { SessionStore } from 'src/app/store/session.service';

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

  logstatus: boolean;
  username: string = environment.defaultuser;
  password: string = environment.defaultuserpwd;
  userattempt: UserForm;
  code = []

  hasPin:  boolean
  loginPreference: string

  sessionStore = SessionStore

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

  ngOnInit() {


    let userData = this.sessionStore.user

    const loginPreference = userData?.LoginPreference
    const pin = userData?.PIN

    if (pin) {
      this.hasPin = true
    } else {
      this.hasPin = false
    }

    if (loginPreference) {
      this.loginPreference = loginPreference
    } else {
      this.loginPreference = ''
    }

  }

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

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

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

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

  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)

        if (attempt) {
          await this.authService.loginChat(this.userattempt);
          await this.getToken();
                      
          this.router.navigate(['/pin']);

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

}
