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 { EXTERNAL_LINKS } from '../../config/constants';
import { AuthService } from '../../services/auth.service';
import { ToasterService } from '../../services/toaster.service';
import { UtilsService } from '../../../oneit/services/utils.service';

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.scss']
})
export class RegisterComponent extends BaseComponent {

    registerForm = {
        username: '',
        firstname: '',
        lastname: '',
        email: '',
        password: '',
        ReferralCode: '',
        was_referred: false,
        terms: false,
        policy: false
    };
    showPassword = false;
    year = new Date().getFullYear();

    @ViewChild('form') form: NgForm;

    constructor(
        private authService: AuthService,
        private toasterService: ToasterService,
        private router: Router,
        private utilsService: UtilsService
    ) {
        super();
    }

    register(): void {
        if (this.form.invalid) {
            return this.utilsService.showAllErrorMessages();
        }
        this.registerForm.email = this.registerForm.username;
        if (!this.registerForm.was_referred) {
            delete this.registerForm.ReferralCode;
        }
        this.isLoading = true;
        this.authService.register(this.registerForm)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                if (response.registered) {
                    this.toasterService.success('Registration successful');
                    this.router.navigate(['/my-career-web/dashboard']);
                }
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            });
    }

    openTermsAndConditions(): void {
        window.open(EXTERNAL_LINKS.TERMS_CONDITIONS, '_blank');
    }

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

}
