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

@Component({
  selector: 'app-customers-add',
  templateUrl: './customers-add.component.html',
  styleUrls: ['./customers-add.component.scss']
})
export class CustomersAddComponent implements OnInit {
  
  public action: string = '';
  public cities: any = [];
  public states: any = [];

  constructor(private title: Title, public apiService: ApiService, public dialogRef: MatDialogRef<CustomersAddComponent>, @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.getStates().subscribe((data:any) => {
      this.states = data.data;
      this.loadCities();
    });  
  }

  ngOnInit() {

  }
  loadCities(evt?:any) {
    this.apiService.getCities(this.data.state).subscribe((data:any) => {
      this.cities = data.data;
    }); 
     
  }
 
  save() {
    this.apiService.saveCustomer(this.data).subscribe((data:any) => {
      if (data.res == "OK") {
        this.dialogRef.close();
      } else {
        this.apiService.showError(data.msg);
      }
    });
  }
  dismiss() {
    this.dialogRef.close();
  }
}
