import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import { ApiService } from '../api.service';
import {Platform} from '@ionic/angular';
import {AppMinimize} from '@ionic-native/app-minimize/ngx';
import AppStorage from '../app.storage';
import AppConfig from '../app.config';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  username = '';
  password = '';
  error: string = null;
  version: string;

  @ViewChild('loginName') usernameElement: ElementRef;
  @ViewChild('loginPassword') passwordElement: ElementRef;

  constructor(private apiService: ApiService, private platform: Platform, private appMinimize: AppMinimize) {
    this.version = AppConfig.VERSION;
  }

  ngOnInit(): void {
    this.platform.backButton.subscribe(
      (t) => {
        this.appMinimize.minimize();
      }
    );

    const lastUsername = AppStorage.getLastLoginName() ?? '';

    if (lastUsername.length > 0) {
      this.username = lastUsername;
    }
  }

  login(event): void
  {
    event.target.disabled = true;
    event.target.classList.add('submit-progress');
    this.error = null;

    this.apiService.getAuthToken(this.username, this.password).toPromise()
      .then(
        (response) => {
          AppStorage.setToken(response.token);

          this.apiService.getChatToken(response.token).toPromise()
            .then(
              (chatTokenResponse) => {
                AppStorage.setChatToken(chatTokenResponse.token);
                AppStorage.setUserId(chatTokenResponse.userId);
                AppStorage.setLastLoginName(this.username);

                window.location.reload();
              }
            ).catch(
            (error) => {
              AppStorage.setToken(null);
              this.error = error.name + ': ' + error.message;

              event.target.disabled = false;
              event.target.classList.remove('submit-progress');
            }
          );
        }
      ).catch (
      (error) => {
        AppStorage.setToken(null);

        switch (error.status) {
          case 401:
            this.error = 'Login fehlgeschlagen: Die Zugangsdaten sind falsch!';
            break;

          case 404:
            this.error = 'API-Fehler: Der Login-Endpunkt konnte nicht gefunden werden!';
            break;

          case 500:
            this.error = 'Server-Fehler: Bitte informiere den Techniker!';
            break;

          case 0:
            this.error = 'Verbindungsfehler: Konnte keine Verbindung zum Server herstellen!';
            break;

          default:
            this.error = 'Fehler: Etwas unfassbar grauenhaftes ist passiert!';
        }

        this.password = '';

        event.target.disabled = false;
        event.target.classList.remove('submit-progress');
      }
    );
  }
}
