import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { first } from 'rxjs/operators';
import { ApiService } from '../api.service';

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

  form: FormGroup;
  timeout: any;
  user_data: any;
  submit_element: HTMLInputElement;

  constructor(private fb: FormBuilder, private dataService: ApiService, private router: Router) {
    this.form = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(5)]],
      password: ['', Validators.required]
    });
  }

  set: NodeListOf<HTMLInputElement>;

  ngOnInit(): void {
    this.submit_element = document.getElementById('submit') as HTMLInputElement;
    this.set = document.querySelectorAll('input:not([type=submit])');
    this.set.forEach(function (item) {
      item.addEventListener('focus', function () {
        item.parentElement.querySelector('label').classList.add('active');
      });
      item.addEventListener('blur', function () {
        if (item.value == "")
          item.parentElement.querySelector('label').classList.remove('active');
      });
    })
  }

  updateLabels() {
    this.set.forEach(function (item) {
      if (item.value !== "" && item.value !== null)
        item.parentElement.querySelector('label').classList.add('active');
      else
        item.parentElement.querySelector('label').classList.remove('active');
    });
  }

  postData(form: FormGroup) {
    if (this.submit_element.classList.contains('disabled')) return;
    this.submit_element.classList.add('disabled');
    
    this.dataService.userLogin(form.value.username, form.value.password)
      .pipe(first())
      .subscribe(data => {
        this.user_data = data;
        const redirect = this.dataService.redirectUrl ? this.dataService.redirectUrl : '/home';
        this.router.navigate([redirect]);
      }, error => {
        this.error("Incorrect username or password.");
        form.get('password').reset();
      });
  }

  error(str: string) {
    let co = (document.getElementById('cover') as HTMLDivElement);
    let pu = (document.getElementById('error') as HTMLDivElement);
    pu.querySelector('.desc').innerHTML = str;

    co.querySelectorAll('.popup').forEach(function (item) {
      item.classList.remove('active');
    });

    co.style.display = "block";
    setTimeout(function () {
      co.classList.add('active');
      pu.classList.add('active');
    }, 100);

    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      pu.classList.remove('active');
      co.classList.remove('active');

      setTimeout(() => {
        co.style.display = 'none';
        this.submit_element.classList.remove('disabled');
      }, 500)
    }, 3000);
  }

  get username() {
    return this.form.get('username');
  }

  get password() {
    return this.form.get('password');
  }

}