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

@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,
        private aps: AppService
    ) {
        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;
            });
    }

    socialMediaLogin(type: 'google' | 'linkedIn') {
        const params = {
            environment: environment.envName,
            nextPage: window.location.href.split('/#/')[0] + '/#/my-career-web/dashboard/home'
        };
        const svc = type === 'linkedIn' ? 'LoginWithLinkedIn' : 'LoginWithGoogle';
        this.isLoading = true;
        this.aps.socicalMediaLogin(svc, params)
            .pipe(takeUntil(this.componentInView))
            .subscribe(data => {
                    this.isLoading = false;
                    if (data.destination) {
                        window.location.href = data.destination;
                        return;
                    }
                },
                err => {
                    this.hs.handleHttpError(err);
                    this.isLoading = false;
                }
            )
    }

    openPrivacyPolicy(): void {
        window.open(EXTERNAL_LINKS.PRIVACY_POLICY, '_blank')
    }

}
