import {Component, Input, OnInit, ViewChild, EventEmitter, Output} from '@angular/core';
import {MessageBoxComponent} from '../../message-box/message-box.component';
import {FileInfo, FileRestrictions, FileSelectComponent, SelectEvent} from '@progress/kendo-angular-upload';
import {AuthService} from '../../service/auth.service';
import {PeopleService} from '../../service/people.service';
import {NgForm} from '@angular/forms';
import {PeopleModel} from '../../models/people.model';

@Component({
  selector: 'app-people-profile',
  templateUrl: './people-profile.component.html',
  styleUrls: ['./people-profile.component.scss']
})
export class PeopleProfileComponent implements OnInit {
  @Input() public People: PeopleModel = PeopleModel.EmptyNew();
  @Output() public newPeople = new EventEmitter<PeopleModel>();

  public avatarUrl = 'url(https://via.placeholder.com/128)' ;
  public myRestrictions: FileRestrictions = {
    allowedExtensions: ['.jpg', '.png', '.jpeg'],
    maxFileSize: 2194304
  };
  @ViewChild('messagebox', {static: true}) msgBox: MessageBoxComponent;
  @ViewChild('fileSelect', {static: true}) fs: FileSelectComponent;

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

  ngOnInit(): void {
    if (this.auth.isAdmin() &&  !this.auth.isCurrentUser(this.People.Id)) {
      //
    }else{
      this.People = this.auth.loggedIn.User;
    }
    this.avatarUrl = 'url(' + this.auth.getUrl('avatar/' + this.People.Id) + ')';
  }

  onDialogClose(status: string): void {
    console.log(status);
  }

  public onSelectAvatar(ev: SelectEvent): void {
    if (ev.files) {
      ev.files.every((file: FileInfo) => {
        if (file.rawFile && !file.validationErrors) {
          const reader  = new FileReader();

          reader.onloadend = () => {
            const str = reader.result as string;

            this.ps.updateAvatar(str, this.People.Id).subscribe( resp => {
              this.avatarUrl = 'url(' + str + ' )';
            }, err => {
              this.msgBox.Show('Failed to Update Avatar: ' + err.toString());
            });
            this.fs.clearFiles();
          };
          reader.readAsDataURL(file.rawFile);
        }else{
          this.msgBox.Show('Only jpg, and png are supported (max 2MB)');
          setTimeout(() => { this.fs.clearFiles(); }, 10);
        }
        return false; // we only take first file
      });
    }
  }


  public save(peopleForm: NgForm): void{
    if (! peopleForm.touched || peopleForm.form.pristine) {
      this.msgBox.Show('Nothing has been changed');
      return;
    }
    this.ps.savePeople(this.People).subscribe( () => {
      this.msgBox.Show('Updated successfully ');
      if ( this.auth.loggedIn.User.Id === this.People.Id ) {
        this.auth.UpdatePeopleInfo(this.People);
      }
      peopleForm.form.markAsPristine();
    }, err => {
      this.msgBox.Show('Failed to Update: ' + err.toString());
    });
  }

  public createPeople(): void{
    this.ps.createPeople(this.People).subscribe(
      ppl => {
          this.People.Copy(ppl);
          this.newPeople.emit(this.People);
          this.avatarUrl = 'url(' + this.auth.getUrl('avatar/' + this.People.Id) + ')';
      }
    );
  }

  public PeopleChanged(ppl: PeopleModel): void {
    console.log(this);
    this.avatarUrl = 'url(' + this.auth.getUrl('avatar/' + this.People.Id) + ')';
  }

  public startSelectAvatar(): void {
    const element: NodeListOf<HTMLElement> = document.getElementsByName('selectAvatar');
    element.forEach( v => {
       if ( v.tagName.toLowerCase() === 'input') {
         v.click();
       }
    });

  }
}
