import { Location } from '@angular/common';
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Directive, Input, NgModule } from '@angular/core';
import { AbstractControl, FormControl, FormGroup, FormsModule, NgForm, NgModel, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import { IApiError, RouterExtService, UserCredentials } from '../core/shared';

import { UserService } from '../core/shared/user/user.service';

import { TranslateService } from '@ngx-translate/core';

export class ResetPasswordBaseComponent implements OnInit {
  lang: string;
  // useremail: string;
  // linkIsSent: boolean = false;
  // submitAttempt: boolean = false;
  // isInvalid: boolean = false;
  // errorMsg: string;
  
  constructor(protected router: Router,
    protected routerExt: RouterExtService,
    protected translateService: TranslateService) {
  }

  ngOnInit(): void {
    this.lang = this.translateService.currentLang || this.translateService.defaultLang;
  }

  getErrorMessage(p: FormControl, key: string): string {
    if (p.hasError('required')) {
      if (key) {
        return 'You must enter a value for \"' + this.translateService.instant(key) + '\"';
      } else {
        return 'You must enter a value';
      }
    }

    if (p.hasError('patternInvalid')) {
      return 'Input format is invalid';
    }
  }

  close(): void {
    this.goToPrevious();
  }

  goToPrevious(): void {
    let previous: string = this.routerExt.getPreviousUrl();
    if (previous) {
      this.router.navigateByUrl(previous);
    } else {
      this.goToHome();
    }
  }

  goToHome(): void {
    this.routerExt.goToHome();
  }

  isFormExists(form: FormGroup | NgForm): boolean {
    return (form instanceof FormGroup) || (form instanceof NgForm);
  }

  isFormValid(form: FormGroup | NgForm): boolean {
    return (this.isFormExists(form) && form.valid);
  }

  isControlExists(control: AbstractControl | NgModel): boolean {
    return (control instanceof AbstractControl) || (control instanceof NgModel);
  }

  isControlDirtyOrTouched(control: AbstractControl | NgModel): boolean {
    return (this.isControlExists(control) && (control.dirty || control.touched));
  }
}

@Component({
  selector: 'knk-resetpassword',
  styleUrls: ['./resetpassword.component.scss'],
  templateUrl: './resetpassword.component.pug'
})
export class ResetPasswordComponent extends ResetPasswordBaseComponent implements OnInit {
  useremail: string;
  linkIsSent: boolean = false;
  submitAttempt: boolean = false;
  isInvalid: boolean = false;
  errorMsg: string;
  
  constructor(protected router: Router,
    protected routerExt: RouterExtService,
    private userService: UserService,
    protected translateService: TranslateService) {
                super(router, 
                  routerExt,
                  translateService);
    this.useremail = '';
  }

  ngOnInit(): void {
    super.ngOnInit();
  }

  sendPasswordReset(): void {
    this.userService.sendPasswordReset(this.useremail, `${window.location}`).subscribe(
      (result) => {
        this.isInvalid = false;
        this.errorMsg = '';
        this.linkIsSent = result;
      },
      (err) => {
        this.isInvalid = true;
        if (err.error.id === -1) {
          err.error.msg = 'An error occurs on the server. Try again later.';
        }
        this.errorMsg = err.error.msg;
        console.error(err);
      });
  }

  onSubmit(form: NgForm): void {
    this.submitAttempt = true;
    if (form.valid) {
      this.sendPasswordReset();
    // } else {
    //   this.errorMsg = 'Please fill all required fields.';
    }
  }
}

@Component({
  selector: 'knk-resetpassword-confirm',
  styleUrls: ['./resetpassword.component.scss'],
  templateUrl: './resetpassword.component.pug'
})
export class ResetPasswordConfirmComponent extends ResetPasswordBaseComponent implements OnInit {
  userpassword: string;
  passwordReset: boolean = false;
  passwordResetError: boolean = false;
  submitAttempt: boolean = false;
  isInvalid: boolean = false;
  errorMsg: string;
  token: string;
  
  constructor(protected router: Router,
              private activatedRoute: ActivatedRoute,
              protected routerExt: RouterExtService,
              private userService: UserService,
              protected translateService: TranslateService) {
    super(router, routerExt, translateService);
    this.userpassword = '';
    this.token = this.activatedRoute.snapshot.params['token'];
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.userService.checkPasswordResetToken(this.token).subscribe(
      (result) => {
        if (result) {
          this.passwordResetError = false;
        } else {
          this.passwordResetError = true;
        }        
      },
      (err) => {
        this.passwordResetError = true;
      });
  }

  resetPassword(): void {
    // e.preventDefault();
    // this.registrationError = null;
    this.userService.resetPassword(this.token, this.userpassword).subscribe(
      (result) => {
        this.passwordReset = result;
      },
      (err) => {
        this.isInvalid = true;
        this.errorMsg = err.error.msg;
        console.error(err);
      });
  }

  onSubmit(form: NgForm): void {
    this.submitAttempt = true;
    if (form.valid) {
      this.resetPassword();
    } else {
      // this.registrationError = {id: -1, msg: 'Please fill all required fields.'};
    }
  }
}
