import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { takeUntil } from 'rxjs/operators';
import { BaseComponent } from '../../base/base.component';
import { AuthService } from '../../services/auth.service';
import { HelperService } from '../../services/helper.service';

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

export class LoginComponent extends BaseComponent {

    year = new Date().getFullYear();

    loginForm = {
        username: '',
        password: ''
    };
    @ViewChild('form') form: NgForm;

    constructor(
        private hs: HelperService,
        private as: AuthService,
        private r: Router
    ) {
        super();
    }

    login(): void {
        if (this.form.invalid) {
            return this.hs.validateAllFormFields(this.form);
        }
        this.isLoading = true;
        this.as.login(this.loginForm)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.hs.oneItHttpResponse(response);
                if (response.status === 'error') {
                    this.loginForm.password = '';

                    return;
                }
                this.r.navigate(['/my-career-web/dashboard']);
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            });
    }

    googleLogin(): void {
        this.isLoading = true;
        this.as.googleLogin()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.hs.oneItHttpResponse(response);
                // if (response.status === 'error') {
                //     this.loginForm.password = '';
                // }
                this.isLoading = false;
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            });
    }

    linkedInLogin(): void {
        this.isLoading = true;
        this.as.linkedinLogin()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.hs.oneItHttpResponse(response);
                // if (response.status === 'error') {
                //     this.loginForm.password = '';
                // }
                this.isLoading = false;
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            });
    }

}
