import { Component, OnInit, Inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ApiService } from 'app/api.service';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
  selector: 'app-users-add',
  templateUrl: './users-add.component.html',
  styleUrls: ['./users-add.component.css']
})
export class UsersAddComponent implements OnInit {
  public action: string = '';
  public statuses: any = [];
  constructor(private title: Title, public apiService: ApiService, public dialogRef: MatDialogRef<UsersAddComponent>, @Inject(MAT_DIALOG_DATA) public data: any) {
    if (this.data.type == 'add') {
      this.action = 'Agregar';
    }
    else if (this.data.type == 'edit') {
      this.action = 'Editar';
    }
    this.statuses.push({id: '1', name: 'Activo'});
    this.statuses.push({id: '0', name: 'Inactivo'});
  }

  ngOnInit() {

  }
  save() {
    this.apiService.saveUser(this.data).subscribe((data:any) => {
      if (data.res == "OK") {
        this.apiService.showOk("Perfecto","Operación realizada con éxito");
        this.dialogRef.close();
      } else {
        this.apiService.showError("Error",data.msg);
      }
    });
  }
  dismiss() {
    this.dialogRef.close();
  }
  
  changeImage(event:any) {
    event.preventDefault();
    let element : HTMLElement = document.getElementById('changeImage') as HTMLElement;
    element.click();
  }
  changeImagePlay(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        this.apiService.loader.emit(true);
        this.apiService.uploadImage(file).subscribe((data:any) => {
          this.apiService.loader.emit(false);
          if (data.res == "OK") {
            this.data.avatar = data.url;
          } else {
            console.log('TODO Error upload');
          }
        });
    }
  }
}
