import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { takeUntil } from 'rxjs/operators';
import { AppService } from '../../../app.service';
import { BaseComponent } from '../../base/base.component';
import { EXTERNAL_LINKS } from '../../config/constants';
import { AuthService } from '../../services/auth.service';
import { HelperService } from '../../services/helper.service';
import { UtilsService } from '../../../oneit/services/utils.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,
        private aps: AppService,
        private us: UtilsService
    ) {
        super();
    }

    login(): void {
        if (this.form.invalid) {
            return this.us.showAllErrorMessages();
        }
        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') {
        this.isLoading = true;
        this.aps.socicalMediaLogin(type)
            .pipe(takeUntil(this.componentInView))
            .subscribe(data => {
                    this.isLoading = false;
                    if (data.destination) {
                        window.location.href = data.destination;
                        return;
                    }
                },
                err => {
                    this.isLoading = false;
                    this.hs.handleHttpError(err);
                }
            )
    }

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

}
