import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { UtilsService } from 'src/app/services/utils.service';
import { ActivatedRoute, Router } from '@angular/router';
import { SubscriptionService } from 'src/app/services/subscription.service';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';

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

  redirect:string = "/";
  email:string;
  password:string;
  loading:boolean = false;

  constructor(private auth:AuthenticationService,
              private utils:UtilsService,
              private activatedRoute:ActivatedRoute,
              private router:Router,
              private subscriptionService:SubscriptionService) { }

  ngOnInit(): void {
    this.subscriptionService.removeSubscription();
    this.setRedirect();
  }

  login(custom_user_id:string = null) {
    this.subscriptionService.removeSubscription();
    if(this.email && this.password && !this.loading) {
      this.loading = true;
      this.auth.login(this.email, this.password, custom_user_id).subscribe(
        data => {
          const ss:SubscriptionSelection[] = data.subscriptions;
          if(data.error && data.error == true) {
            this.utils.showMessage("error", "Acceso no válido", data.message);
            this.loading = false;
          }
          else if(this.isSuperAdmin(ss)) {
            this.auth.logout();
            this.loading = false;
            const custom_user_id:string = window.prompt("Has iniciado sesión como super administrador. Por favor, introduce el identificador de usuario que quieres impersonar:");
            if(custom_user_id!=null) {
              this.login(custom_user_id);
            }
          }
          else {
            this.navigateRedirect(500);
          }
        },
        error => {
          this.utils.showMessage("error", "Acceso no válido", "Tu contraseña puede ser incorrecta, o bien puede ser que no tengas permisos.");
          this.loading = false;
        }
      );
    }
    else {
      this.utils.showMessage("error", "Introduce todos los datos", "Introduce un correo electrónico válido y una contraseña.");
      this.loading = false;
    }
  }

  private setRedirect() {
    const queryRedirect:string = this.activatedRoute.snapshot.queryParamMap.get("redirect");
    if(queryRedirect!=null) {
      this.redirect = queryRedirect;
    }
  }

  private navigateRedirect(time:number = 1500) {
    const self = this;
    setTimeout(() => {
      self.router.navigate([self.redirect], { queryParams: { "start": 1 } });
    }, time);
  }

  private isSuperAdmin(ss:SubscriptionSelection[]):boolean {
    let trobat:boolean = false;
    let i = 0;
    while(!trobat && i<ss.length) {
      if(ss[i].role.slug == "super_admin") trobat = true;
      i++;
    }
    return trobat;
  }

}
