import { Component, OnInit, 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';

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

    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();
    }

    ngOnInit(): void {
        //
    }

    register(): void {
        if (this.form.invalid) {
            return this.hs.validateAllFormFields(this.form);
        }
        this.registerForm.firstname = 'AA';
        this.registerForm.lastname = 'BB';
        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);
            });
    }

}
