import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
import {AuthService} from '../../service/auth.service';
import {PeopleService} from '../../service/people.service';
import {MessageBoxComponent} from '../../message-box/message-box.component';

@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: ['./change-password.component.scss']
})
export class ChangePasswordComponent implements OnInit {
  @Input() PeopleId = '';
  @ViewChild('messageBox', {static: true}) msgBox: MessageBoxComponent;

  public changePassword = false;
  public isAdmin = false;

  public ChangePassForm: FormGroup = new FormGroup({
    OldPassword: new FormControl(),
    NewPass: new FormControl(),
    NewPass1: new FormControl(),
  });
  constructor(private auth: AuthService, private ps: PeopleService) { }

  ngOnInit(): void {
    if (this.auth.isAdmin() && this.PeopleId !== '' && !this.auth.isCurrentUser(this.PeopleId)) {
      this.isAdmin = this.auth.isAdmin();
    }
  }
  public hidePass(): void{
    if ( this.changePassword ) {
      this.ChangePassForm.reset();
    }
  }

  public savePassword(): void{
    this.ps.savePassword(this.PeopleId, this.ChangePassForm.value).subscribe(
      () => {
        this.changePassword = false;
        this.msgBox.Show('Password Changed');
      }, err => {
        this.msgBox.Show('Failed to Change Password :' + err.toString());
      }
    );
  }

  public passwordEqual(): boolean{
    const v = this.ChangePassForm.value;
    if ( this.ChangePassForm.valid && v.NewPass === v.NewPass1 && this.ChangePassForm.touched && v.NewPass1 !== '') {
      return true;
    }else{
      this.ChangePassForm.get('NewPass1').setErrors({incorrect: true});
    }
    return false;
  }

  public canChangePassword(): boolean {
    if ( this.auth.isCurrentUser(this.PeopleId) ) {
      return this.auth.isUser() || this.auth.isBroker() || this.auth.isAdmin();
    }else{
      return this.auth.isAdmin() ;
    }
  }
}
