import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {UserExtraModel} from '../../models/user-extra.model';
import {FormControl, FormGroup, NgForm, Validators} from '@angular/forms';
import {AuthService} from '../../service/auth.service';
import {HttpClient} from '@angular/common/http';
import {MessageBoxComponent} from '../../message-box/message-box.component';
import {PeopleService} from '../../service/people.service';
import {asyncValidatorLoginAvailable} from '../../validator/unique.login.validator';
import {PeopleModel} from '../../models/people.model';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {
  @Input() public People: PeopleModel = PeopleModel.EmptyNew();
  @Input() public UserExtra: UserExtraModel = UserExtraModel.EmptyNew();
  @ViewChild('messageBox', {static: true}) msgBox: MessageBoxComponent;

  public showAdmin = false;
  public isCurrentUser = false;

  public UserForm: FormGroup;

  constructor(private auth: AuthService, private http: HttpClient, private ps: PeopleService) { }

  ngOnInit(): void {

    this.showAdmin = this.auth.isAdmin();
    this.isCurrentUser = this.auth.isCurrentUser(this.People.Id);

    if (this.auth.isAdmin() &&  !this.auth.isCurrentUser(this.People.Id)) {
      // edit other people,
    }else{
      this.People.Id = this.auth.loggedIn.User.Id;
      this.UserExtra = this.auth.loggedIn.UserExtra;
    }
    this.UserForm = new FormGroup({
      Login: new FormControl({value: this.UserExtra.Login, disabled: ! this.showAdmin },
        [Validators.required, Validators.email],
        [asyncValidatorLoginAvailable(this.auth, this.UserExtra.Login)] )
    });
  }

  public save(): void {
    const ex = new UserExtraModel(this.UserExtra);
    ex.Login = this.UserForm.get('Login').value;

    this.http.post<UserExtraModel>(this.auth.getUrl('user/' + this.People.Id), ex).subscribe(
       resp => {
         if ( resp.Login === ex.Login) {
           this.UserExtra.Login = resp.Login;
           this.msgBox.Show('Successfully Changed');
         }else{
           this.msgBox.Show('Login not Changed: ' + resp );
         }
       }, err => {
          this.msgBox.Show('Error Occurred'  + err.toString());
       }
    );
  }

  public currentUserIsAdmin(): boolean {
    return this.auth.loggedIn.role === 'admin';
  }

  public canEditUser(): boolean {
    return this.UserExtra !== undefined && this.UserExtra.Login !== undefined;
  }


  public showSubmit(): boolean {
    return this.UserForm.get('Login').status !== 'PENDING' && this.currentUserIsAdmin();
  }

}
