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 {PeopleProfileComponent} from './people-profile/people-profile.component';
import {BrokerProfileComponent} from './broker-profile/broker-profile.component';
import {UserProfileComponent} from './user-profile/user-profile.component';
import {ActivatedRoute} from '@angular/router';
import {BrokerModel} from '../models/broker.model';
import {PeopleModel} from '../models/people.model';
import {UserExtraModel} from '../models/user-extra.model';
import {MessageBoxComponent} from '../message-box/message-box.component';
import {setTime} from '@progress/kendo-angular-dateinputs/dist/es2015/util';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit {
  @Input() PeopleId = '';
  @ViewChild('peopleProfile', {static: true}) pp: PeopleProfileComponent;
  @ViewChild('userProfile', {static: true}) up: UserProfileComponent;
  @ViewChild('brokerProfile', {static: true}) bp: BrokerProfileComponent;
  @ViewChild('messagebox', {static: true}) msgBox: MessageBoxComponent;

  public role = 'unknown'; // the role user to be edited.
  public UserExtra: UserExtraModel = UserExtraModel.EmptyNew();
  public People: PeopleModel = PeopleModel.EmptyNew();

  // different section
  public showUser = false;
  public showBroker = false;
  public showAdmin = false;
  public showPassword = false;

  // admin specific
  public showAdminTool = false;
  public editOtherPeople = false;
  public enableUserAdd = false;
  public enableUserDel = false;
  public enableBrokerAdd = false;
  public enableBrokerDel = false;

  // delete entire people
  public warnDelete = false;
  public deleteHeight = 25;
  private countDownNumber = -1;
  private timer = null;
  public label = {
    visible: false,
    position: 'start',
    format: 'percent'
  };
  //
  public isValidPeople = true;
  public isValidBroker = true;

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

  ngOnInit(): void {
    const id  = this.actRoute.snapshot.params.id;
    if ( id !== undefined && id.length > 10 ) {
        this.PeopleId = id;
    }

    if (this.auth.isAdmin()  && this.PeopleId !== '' ){
      if  (this.PeopleId === 'start-new-people' ){
        return;
      }else if (this.PeopleId !== '' && !this.auth.isCurrentUser(this.PeopleId)) { // admin editing someone else
        this.loadOtherPeople();
      }
    }else { // edit himself
      this.role = this.auth.loggedIn.role;
      this.PeopleId = this.auth.loggedIn.User.Id;
      this.People = this.auth.loggedIn.User;
      this.UserExtra = this.auth.loggedIn.UserExtra;
    }
    this.updateShowHide();
  }

  private loadOtherPeople(): void {
    this.isValidPeople = false;
    this.ps.getPeopleById(this.PeopleId).subscribe(
      ppl => {
        this.isValidPeople = ppl.Id === this.PeopleId;
        if (this.isValidPeople) {
          console.log(this);
          this.People.Copy(ppl);
          this.pp.PeopleChanged(this.People);
          this.loadOtherPeopleExtra();
        }
        this.updateShowHide();
      }, err => {
        console.log(this);
        this.msgBox.Show('Failed to load User Information');
      }
    );
  }

  private loadOtherPeopleExtra(): void {
    this.isValidBroker = false;
    this.ps.getPeopleExtraById(this.PeopleId).subscribe(
      resp => {
        this.setUserExtra(resp);
        this.updateShowHide();
      }
    );
  }

  private setUserExtra(resp: UserExtraModel): void {
    this.isValidBroker = resp.License !== '';
    this.UserExtra.Copy(resp);
    this.role = this.UserExtra.Role;
  }

  private updateShowHide(): void {
    this.resetShowHide();

    this.editOtherPeople = ! this.auth.isCurrentUser(this.PeopleId);
    if ( this.editOtherPeople ) {
      this.showAdminTool = this.isAdmin() && this.People.Id !== '' ;
      if ( this.showAdminTool ){
        this.enableUserAdd = ! ['user', 'broker', 'admin'].includes(this.role);
        this.enableUserDel = this.role === 'user';
        this.enableBrokerAdd = this.role === 'user';
        this.enableBrokerDel = this.role === 'broker';
      }

      this.showUser = ['user', 'broker', 'admin'].includes(this.role);
      this.showBroker = ['broker'].includes(this.role);
      this.showAdmin = ['admin'].includes(this.role);
      this.showPassword = this.showUser;

    }else{
      this.showAdminTool = false;
      this.showUser = ['user', 'broker', 'admin'].includes(this.role);
      this.showBroker = ['broker'].includes(this.role);
      this.showAdmin = ['admin'].includes(this.role);
      this.showPassword = ['user', 'broker', 'admin'].includes(this.role);
    }
  }

  private resetShowHide(): void {
    // different section
    this.showUser = false;
    this.showBroker = false;
    this.showAdmin = false;
    this.showPassword = false;

    // admin specific
    this.showAdminTool = false;
    this.editOtherPeople = false;
    this.enableUserAdd = false;
    this.enableUserDel = false;
    this.enableBrokerAdd = false;
    this.enableBrokerDel = false;
  }

  public onNewPeopleCreated(ppl: PeopleModel): void {
    this.updateShowHide();
  }

  // the user who performs this edit action
  public isAdmin(): boolean {
      return this.auth.isAdmin();
  }

  // the user who performs this edit action
  public isBroker(): boolean {
      return this.auth.isBroker();
  }

  // the user who performs this edit action
  public isUser(): boolean {
      return this.auth.isUser();
  }

  public deletePeople(): void {

    this.ps.deletePeople(this.People.Id).subscribe(
      resp => {
          if ( resp === this.People.Id ) { // successfully deleted
            this.msgBox.Show('User and all of his/her related loans payment has been deleted !!');
            this.People.Clear();
            this.UserExtra.Clear();
            this.role = 'unknown';
            console.log(this);
            this.updateShowHide();
          }
        }, err => {
          this.msgBox.Show('"Error Delete People');
        }
    );
  }

  public upgradePeopleToUser(): void{
    this.ps.upgradePeopleToUser(this.People.Id).subscribe(
      resp => {
        this.setUserExtra(resp);
        this.updateShowHide();
      }
    );
  }

  public downgradeToPeople(): void{
    this.ps.downgradeUserToPeople(this.People.Id).subscribe(
      resp => {
        this.setUserExtra(resp);
        this.updateShowHide();
      }
    );
  }

  public upgradeUserToBroker(): void{
    this.ps.upgradeUserToBroker(this.People.Id).subscribe(
      resp => {
        this.setUserExtra(resp);
        this.updateShowHide();
      }
    );
  }

  public downgradeToUser(): void{
    this.ps.downgradeBrokerToUser(this.People.Id).subscribe(
      resp => {
        this.setUserExtra(resp);
        this.updateShowHide();
      }
    );
  }

  public onWarnDelete(status: boolean): void {

      if (status) {
        this.deleteHeight = 100;
        this.countDown();
      }else{
        this.deleteHeight = 30;
      }
  }

  private countDown(): void {
    if ( ! this.timer ) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    this.countDownNumber = 100;
    this.timer = setInterval(() => {
      this.countDownNumber --;

      if ( this.countDownNumber <= 0 ){
        clearTimeout(this.timer);
        this.timer = null;
        this.warnDelete = false;
        this.deleteHeight = 30;
      }
    }, 100); // 3ms, total 300ms = 5 seconds
  }
}
