import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';

@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 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');
    });
  }

  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);
  }

}
