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';

@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
    ) {
        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) {
                    console.log('Registered');
                }
            }, err => {
                this.isLoading = false;
                this.hs.handleHttpError(err);
            });
    }

}
