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

@Component({
  selector: 'app-catalog-category-add',
  templateUrl: './catalog-category-add.component.html',
  styleUrls: ['./catalog-category-add.component.scss']
})
export class CatalogCategoryAddComponent implements OnInit {

  public categories: any = [];
  public action: string = '';

  constructor(private title: Title, public apiService: ApiService, public dialogRef: MatDialogRef<CatalogCategoryAddComponent>, @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.apiService.getCategories().subscribe((data:any) => {
      this.categories = [];
      this.categories.push({id: '0', name: '- Superior -'});
      for (let i=0;i< data.data.length;i++) {
        if(data.data[i].parent=='0') { this.categories.push({id: data.data[i].id, name: data.data[i].name}); }
      }
    });
  }

  ngOnInit() {

  }
  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.banner = data.url;
          } else {
            console.log('TODO Error upload');
          }
        });
    }
  }
  save() {
    this.apiService.saveCategory(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();
  }

}
