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 { UtilsService } from '../../../oneit/services/utils.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 authService: AuthService,
        private router: Router,
        private appService: AppService,
        private utilsService: UtilsService,
        private helperService: HelperService
    ) {
        super();
    }

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

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

    socialMediaLogin(type: 'google' | 'linkedIn') {
        this.isLoading = true;
        this.appService.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.utilsService.handleError(err);
                }
            )
    }

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

}
