import { Component, Directive, ElementRef, Host, HostListener, Input, OnDestroy, OnInit } from '@angular/core';

import { ActivatedRoute, Router } from '@angular/router';

import { RouterExtService, TokenService, UserCredentials } from '../core/shared';

import { AbstractControl, FormControl, FormGroup, NgForm, NgModel } from '@angular/forms';

import { BaseComponent } from '../core/components/base.component';
import { TranslateService } from '@ngx-translate/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'knk-login',
  styleUrls: ['./login.component.scss'],
  templateUrl: './login.component.pug'
})
export class LoginComponent implements OnInit, OnDestroy {
  lang: string;
  user: UserCredentials;
  isLoginInvalid: Boolean = false;
  errorMsg: string;
  private ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(private router: Router,
              private activatedRoute: ActivatedRoute,
              private routerExt: RouterExtService,
              private tokenService: TokenService,
              private translateService: TranslateService) {
    this.user = new UserCredentials();
  }

  ngOnInit(): void {
    this.lang = this.translateService.currentLang || this.translateService.defaultLang;
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  close(): void {
    this.goToPrevious();
  }

  goToPrevious(): void {
    let previous: string = this.routerExt.getPreviousUrl();
    if (previous) {
      this.router.navigateByUrl(previous);
    } else {
      this.goToHome();
    }
  }

  goToHome(): void {
    this.routerExt.goToHome();
  }

  login(): void {
    this.tokenService.apiUserToken(this.user).subscribe(() => {
        this.goToHome();
        // this.router.navigate(['..', 'dashboard'], { relativeTo: this.route.parent });
      },
      (err) => {
        this.isLoginInvalid = true;
        this.errorMsg = err.msg;
        console.error(err);
      }
    );
  }

  getErrorMessage(p: FormControl, key: string): string {
    if (p.hasError('required')) {
      if (key) {
        return 'You must enter a value for \"' + this.translateService.instant(key) + '\"';
      } else {
        return 'You must enter a value';
      }
    }

    if (p.hasError('patternInvalid')) {
      return 'Input format is invalid';
    }
  }

  onSubmit(form: NgForm): void {
    if (form.valid) {
      Observable.timer(1000).takeUntil(this.ngUnsubscribe).subscribe((): void => {
        this.ngUnsubscribe.next();
        this.login();
      });
    } else {
      for (let i in form.controls) {
        form.controls[i].markAsTouched();
      }
    }
  }

  isFormExists(form: FormGroup | NgForm): boolean {
    return (form instanceof FormGroup) || (form instanceof NgForm);
  }

  isFormValid(form: FormGroup | NgForm): boolean {
    return (this.isFormExists(form) && form.valid);
  }

  isControlExists(control: AbstractControl | NgModel): boolean {
    return (control instanceof AbstractControl) || (control instanceof NgModel);
  }

  isControlDirtyOrTouched(control: AbstractControl | NgModel): boolean {
    return (this.isControlExists(control) && (control.dirty || control.touched));
  }

  // @HostListener('window:keyup.enter', ['$event', 'undefined'])
  // onEnterOrClick(enterEvent: Event, mouseEvent: Event): void {
  //    this.login();
  // }
}
