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 { ToasterService } from '../../services/toaster.service';
import { EXTERNAL_LINKS } from '../../config/constants';
import { UtilsService } from '../../../oneit/services/utils.service';
import { HelperService } from '../../services/helper.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 activatedRoute: ActivatedRoute,
        private toasterService: ToasterService,
        private authService: AuthService,
        private utilsService: UtilsService,
        private helperService: HelperService,
        private router: Router
    ) {
        super();
    }

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

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

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

}
