import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { environment } from '../../../environments/environment';

import { AuthService } from '../../services/auth.service';

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

  @ViewChild('loginForm') loginForm: ElementRef;
  autologin: boolean = false;
  loginInvalid: boolean;
  externalLoginInvalid: boolean;
  apiUrl = environment.apiUrl;
  targetRoute: string;
  externals: any[];
  username: string = '';

  constructor(
    private authService: AuthService,
    private router: Router,
    private route: ActivatedRoute) { }

  async ngOnInit() {
    this.route.queryParams.subscribe({
      next: (params) => {
        if (params['target']) {
          this.targetRoute = params['target'];
          this.router.navigate([], { queryParams: { target: null }, queryParamsHandling: 'merge', replaceUrl: true });
        }
        if (params['error'] || params['error'] == '') {
          this.loginInvalid = true;
          this.router.navigate([], { queryParams: { error: null }, queryParamsHandling: 'merge', replaceUrl: true });
        }
        if (params['username']) {
          this.username = params['username'];
          this.router.navigate([], { queryParams: { username: null }, queryParamsHandling: 'merge', replaceUrl: true });
        }
        if (params['externalError'] || params['externalError'] == '') {
          this.externalLoginInvalid = true;
          this.router.navigate([], { queryParams: { externalError: null }, queryParamsHandling: 'merge', replaceUrl: true });
        }
      }
    });

    this.authService.getExternal().subscribe({
      next: (data: any[]) => {
        this.externals = data;
        const autologinClient = localStorage.getItem("buntspecht.autologin");
        for (let client of this.externals) {
          if (client.id == autologinClient) {
            window.location.href = this.apiUrl + "/" + client.loginUrl;
          }
        }
      }
    })

  }

  ngAfterViewInit(): void {
    if (this.targetRoute) {
      this.loginForm.nativeElement.action = this.loginForm.nativeElement.action + "?forward=" + window.location.origin + encodeURIComponent(this.targetRoute);
    }
  }

  externalLogin(client: any): void {
    if (this.autologin) {
      localStorage.setItem("buntspecht.autologin", client.id);
    } else {
      localStorage.removeItem("buntspecht.autologin");
    }

    window.location.href = this.apiUrl + "/" + client.loginUrl;
  }

}
