import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { CookieService } from 'ngx-cookie-service';
import { LOGIN_API, REGISTER_API } from '../urls';
import { LoginResponse, RegisterResponse } from '../responses';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';

/**
 * This component render login page.
 */
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  email = new FormControl('', [Validators.required, Validators.email]);
  password = new FormControl('', [Validators.required]);
  //Following observables created to monitor communication of login as well as register with the server.
  login_stat$ = new Observable<LoginResponse>;
  register_stat$ = new Observable<RegisterResponse>;
  
  getErrorMessage() {
    if (this.email.hasError('required')) {
      return 'You must enter a value';
    }
    return this.email.hasError('email') ? 'Not a valid email' : '';
  }
  
  constructor(private cookieService: CookieService, private http:HttpClient, private router: Router) {}
  
  /**
   * If login is clicked this function create a response to be posted to backend server with the email and password.
   * If Authenticated, it will set the cookie for the user.
   */
  login() {
    
    this.login_stat$ = this.http.post<LoginResponse>(LOGIN_API, {
      email: this.email.value,
      password: this.password.value
    });
    this.login_stat$.subscribe(
      (response) => {
        console.log(response);
        if (response.status == true) {
          this.cookieService.set('email', response.email);
          this.cookieService.set('uid',response.uid);
          this.router.navigate(['/home']);
        } 
        else{
          alert('Invalid Credentials');
        }
      }
    );
    
    this.setCookie('email',String(this.email.value));
    this.setCookie('password',String(this.password.value));
    this.setCookie('login','true');

  }

  /**
   * If register is clicked this function create a response to be posted to backend server with the email and password.
   * This will create a new user. Other values such as first name and last need to be modified by user using Profile page.
   * Newly, regustered user will not have any project under his belt hence will see a blank home page.
   */
  register(){
    this.register_stat$ = this.http.post<RegisterResponse>(REGISTER_API, {
      email: this.email.value,
      password: this.password.value,
      role: 'employee',
      first_name: 'Jon',
      last_name: 'Snow',
    });
    this.register_stat$.subscribe(
      (response) => {
        console.log(response);
        if (response.status == true) {
          this.cookieService.set('uid', response.uid);
          this.router.navigate(['/home']);
        } 
        else{
          alert('Registration Failed Try Later');
        }
      }
    );
    this.setCookie('email',String(this.email.value));
    this.setCookie('password',String(this.password.value));
    this.setCookie('login','true');
  }
  setCookie(name: string,value: string){
    this.cookieService.set(name,value);
  }
  getCookie(name: string){
    return this.cookieService.get(name);
  }
  deleteCookie(name: string){
    this.cookieService.delete(name);
  }

  ngOnInit(): void {

  }

}
