import { Component, HostListener, OnInit } from '@angular/core';

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

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

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

import { BaseComponent } from '../core/components/base.component';

@Component({
    selector: 'knk-login',
    styleUrls: ['./login.component.scss'],
    templateUrl: 'login.component.html'
})
export class LoginComponent extends BaseComponent implements OnInit {
    user: UserCredentials;
    isLoginInvalid: Boolean = false;
    errorMsg: string;
    constructor(private router: Router,
        route: ActivatedRoute,
        private tokenService: TokenService) {
            super(null, route);
            this.user = new UserCredentials();

    }
    ngOnInit(): void {
        // console.log('init');
        super.ngOnInit();
    }
    login(): void {
        this.tokenService.apiUserToken(this.user).subscribe(() => {
                this.router.navigate([this.lang, `feeds`]);
                // this.router.navigate(['..', 'dashboard'], { relativeTo: this.route.parent });
            },
            (err) => {
                this.isLoginInvalid = true;
                console.log(err);
                this.errorMsg = err.msg;
            }
        );
    }
    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(f: NgForm): void {
        if (f.valid) {
            this.login();
        } else {
            for (let i in f.controls) {
                f.controls[i].markAsTouched();
              }
        }
    }

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