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 { ClearStoreService } from 'src/app/services/clear-store.service';
import { ChangeProfileService } from 'src/app/services/change-profile.service';
import { ThemeService } from 'src/app/services/theme.service';
import { StorageService } from 'src/app/services/storage.service';

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

  logstatus: boolean;
  username: string = SessionStore.user.Email || 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 clearStoreService: ClearStoreService,
    private changeProfileService: ChangeProfileService,
    public ThemeService: ThemeService,
    private storageservice: StorageService,
  ) {}

  ngOnInit() {
   this.storageservice.get('theme').then((theme) =>{
     console.log('LOGIN THEME',theme)
     this.ThemeService.setTheme(theme)
   })
  }

  //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.requestPermissions();
    this.notificatinsservice.registrationError();
    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: ""
        }

        const loader = this.toastService.loading()

        let attempt = await this.authService.login(this.userattempt, {saveSession: false})

        loader.remove()

        if (attempt) {

          if (attempt.UserId == SessionStore.user.UserId) {
            await this.authService.SetSession(attempt, this.userattempt);
            await this.authService.loginChat(this.userattempt);
            this.getToken();
            SessionStore.setInativity(true);

            this.goback()
          } else {

            this.clearStoreService.clear()
            SessionStore.delete()
            window.localStorage.clear();

            await this.authService.SetSession(attempt, this.userattempt);

            this.changeProfileService.run()
            await this.authService.loginChat(this.userattempt);
            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');
    }
  }

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

  }

}
