import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {AuthService} from '../../service/auth.service';
import {NgForm} from '@angular/forms';
import {PeopleService} from '../../service/people.service';
import {BrokerModel} from '../../models/broker.model';
import {MessageBoxComponent} from '../../message-box/message-box.component';
import {UserExtraModel} from '../../models/user-extra.model';
import {PeopleModel} from '../../models/people.model';



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

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

  ngOnInit(): void {
    this.isAdmin = this.auth.isAdmin();
  }

  public save(brokerForm: NgForm): void{
    if (! brokerForm.touched || brokerForm.form.pristine) {
      this.msgBox.Show('Save successfully done');
      return;
    }
    const broker = BrokerModel.getFromUserAndExtra(this.People, this.UserExtra);
    this.ps.saveBroker(broker).subscribe( () => {
      this.msgBox.Show('updated successfully ');
      brokerForm.form.markAsPristine();
    }, err => {
      this.msgBox.Show('Failed to Update: ' + err.toString());
    });
  }

}
