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

@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 hs: HelperService,
        private as: AuthService,
        private ts: ToasterService,
        private r: Router
    ) {
        super();
    }

    register(): void {
        if (this.form.invalid) {
            return this.hs.validateAllFormFields(this.form);
        }

        this.registerForm.firstname = this.registerForm.username.split('@').pop();
        this.registerForm.lastname = this.registerForm.firstname;
        this.registerForm.email = this.registerForm.username;
        if (!this.registerForm.was_referred) {
            delete this.registerForm.ReferralCode;
        }
        this.isLoading = true;
        this.as.register(this.registerForm)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.hs.oneItHttpResponse(response);
                if (response.registered) {
                    this.ts.success('Registration successful');
                    this.r.navigate(['/my-career-web/dashboard']);
                }
            }, err => {
                this.isLoading = false;
                this.hs.handleHttpError(err);
            });
    }

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

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

}
