import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { FormControl, FormGroup, Validators } from "@angular/forms";
import { TitleService } from "src/app/shared/services/title.service";
import { AuthService } from "src/app/shared/server-services/auth.service";
import { DialogService } from "src/app/shared/services/dialog.service";

@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.scss"],
})
export class LoginComponent implements OnInit {
  public isPending: boolean = false;
  public isLoginSuccess: boolean = false;
  

  loginForm = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required]),
    rememberMe: new FormControl(false)
  });

  constructor(
    private authService: AuthService,
    private router: Router,
    private dialogService: DialogService,
    private titleService: TitleService
  ) {
    this.titleService.setTabTitle(marker("Login"));
  }

  ngOnInit(): void {}

  public startLogin() {
    const email = this.loginForm.get("email").value;
    const password = this.loginForm.get("password").value;
    const rememberMe = this.loginForm.get("rememberMe").value;

    this.isPending = true;
    this.authService
      .login(email, password, undefined, undefined, undefined, rememberMe)
      .then(() => {
        console.log("login OK");
        this.isPending = false;
        this.isLoginSuccess = true;
        this.router.navigate(["/"]);
      })
      .catch((err) => {
        console.log("login FAIL", err);
        this.isLoginSuccess = false;
        this.isPending = false;
        if (err.success === false) {
          this.dialogService.openAlertDialog(
            marker("Login Error"),
            marker("Invalid credentials. Please try again."),
            err.err.message + "; "+ err.err.stack
          );
        } else if (err.serverError === true) {
          this.dialogService.openAlertDialog(
            marker("Login Error"),
            marker("Can not connect to the server. Please try again later."),
            err.err.message + "; "+ err.err.stack
          );
        } else if (err.clientError === true) {
          this.dialogService.openAlertDialog(
            marker("Login Error"),
            marker(
              "Client can not setup the user workspace. Please try again. If you can not login please contact our support team."
            ), err.err.message + "; "+ err.err.stack
          );
        }
      });
  }
}
