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

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

    year = new Date().getFullYear();
    resetForm = {
        password: '',
        confirmPassword: ''
    };
    resetToken;
    showPassword = false;

    @ViewChild('form') form: NgForm;

    constructor(
        private hs: HelperService,
        private ar: ActivatedRoute,
        private ts: ToasterService,
        private as: AuthService,
        private r: Router
    ) {
        super();
    }

    ngOnInit(): void {
        this.ar.params
            .pipe(takeUntil(this.componentInView))
            .subscribe(params => {
                if (params.token) {
                    this.resetToken = params.token;
                }
            });
    }

    reset(): void {
        if (this.form.invalid) {
            return this.hs.validateAllFormFields(this.form);
        }
        const formData = {resetToken: this.resetToken, newPassword: this.resetForm.password};
        this.isLoading = true;
        this.as.reset(formData)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.hs.oneItHttpResponse(response);
                if (response.passwordChanged) {
                    this.ts.success('Password changed.');
                    this.r.navigate(['/my-career-web/auth/login']);
                }
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            });
    }

}
