import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { NgCortexService } from '@ng-cortex/core';

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

  _loginForm: FormGroup = null;
  _loginLoading = false;

  private _loginSubscription: Subscription = null;

  constructor(
    private _formBuilder: FormBuilder,
    private _ncSrv: NgCortexService
  ) { }

  ngOnInit() {
    this._loginForm = this._formBuilder.group({
      login: [null, [Validators.required]],
      password: [null, [Validators.required]],
      rememberMe: [true, [Validators.required]]
    });
  }

  ngOnDestroy() {
    this._loginSubscription && this._loginSubscription.unsubscribe();
  }

  _login() {
    const controls = this._loginForm.controls;
    for (const name in controls) {
      controls[name].markAsDirty();
      controls[name].updateValueAndValidity();
    }
    if (this._loginForm.valid) {
      const { login, password, rememberMe } = this._loginForm.value;
      this._loginLoading = true;
      this._loginSubscription = this._ncSrv.login(login, password, rememberMe)
        .subscribe(() => this._loginLoading = false);
    }
  }

}

