import { UserDTO } from './../../models/User';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';

import { UsersService } from './../services/users.service';
import { LoggedUserService } from '../services/logged-user.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public userForm: FormGroup

  public user: UserDTO

  public users: UserDTO[] = []
  public usersNames: string[] = []
  public usersEmails: string[] = []

  public hide: boolean = true

  constructor(private fb:FormBuilder,
    private _router: Router,
    private _usersService: UsersService,
    private _loggedUser: LoggedUserService) { }

  ngOnInit(): void {
    this.getUsers()
    this.createForm();
  };

  public createForm(): void {
    this.userForm = this.fb.group({
      name: new FormControl('', [Validators.required]),
      password: new FormControl('', [Validators.required])
    })
  };

  public onSubmit(): void {
    const nameOrEmail: string = this.userForm.getRawValue().name
    const password: string = this.userForm.getRawValue().password

    if(nameOrEmail === 'admin' && password === '123') {
      this._router.navigate(['home-admin'])
      return;
    }

    if((this.usersNames.includes(nameOrEmail) || this.usersEmails.includes(nameOrEmail)) && password === '123') {
      this.user =  this.users.find(user => user.name === nameOrEmail || user.email === nameOrEmail)
      // this._loggedUser.loggedUser = this.user
      localStorage.setItem("name", this.user.name)
      localStorage.setItem("email", this.user.email)
      this._router.navigate(['home-user'])
    } else {
      alert('Usuário ou senha incorreto !!!!!!')
    }
  };

  public getUsers(): any {
    this._usersService.getUsers().subscribe(users => {
      users.forEach(user => {
        this.users.push(user)
        this.usersNames.push(user.name)
        this.usersEmails.push(user.email)
      })
    });
  }
};
