import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { Authentication, SessionType } from '../../../services/Authentication';

@Component({
  selector: 'account-login',
  templateUrl: './login.component.html',
  imports: [ FormsModule, CommonModule ],
  standalone: true
})
export class LoginComponent {
  UserName: string = "";
  Password: string = "";
  StayLoggedIn: boolean = false;
  errorMsgs: string[] = [];
  returnURL: string = '/';

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication ) {
    this.title.setTitle("Login | Mistox");
    this.route.queryParams.subscribe(params => {
      this.returnURL = params['returnURL'] || '/';
    });
  }

  onSubmit() {
    this.errorMsgs = [];

    if (!this.UserName) {
      this.errorMsgs.push("The 'username' field is required");
    }
    if (!this.Password) {
      this.errorMsgs.push("The 'password' field is required");
    }
    if (this.Password.length < 6) {
      this.errorMsgs.push("Password must be at least 6 Characters long");
    }
    if (this.errorMsgs.length > 0) {
      return;
    }

    this.errorMsgs.push("Waiting for response from server");
    this.auth.Login(this.UserName, this.Password, this.StayLoggedIn).subscribe({
      next: data => {
        this.router.navigate([this.returnURL]);
      },
      error: err => {
        this.errorMsgs = [ err.error ];
      }
    })
  }
}