import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PlantsService } from '@app/services/plants.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-new-plant',
  templateUrl: './new-plant.component.html',
  styleUrls: ['./new-plant.component.scss']
})
export class NewPlantComponent implements OnInit {
  title:string = "Nueva planta"; 
  assetForm: FormGroup;
  submitted: boolean = false;
  role_number: any;
  distributor = ["EEO","CAESS","DELSUR","CLESA","DEUSEM","ABRUZZO","EDESAL","B&D","DEL SUR"];
  
  categoria_tarifaria = [
    { key: "PD", value: "PD Pequeña Demanda" },
    { key: "MD", value: "MD Mediana Demanda" },
    { key: "GD", value: "GD Gran Demanda" }
  ];

  codigo_tarifa = [
    { key:"R", value: "R Residencial" },
    { key:"G", value: "G General" },
    { key:"AP", value: "AP Alumbrado Público" },
    { key:"MD CMP - BT" ,value: "MD CMP-BT Mediana Demanda Con Medicion de Potencia Baja Tensión" },
    { key:"MD CMP - MT" ,value: "MD CMP-MT Mediana Demanda Con Medicion de Potencia  Media Tensión" },
    { key:"MD CMH - BT" ,value: "MD CMH-BT Mediana Demanda Con Medicion Horaria Baja Tensión" },
    { key:"MD CMH - MT" ,value: "MD CMH-MT Mediana Demanda Con Medicion Horaria Media Tensión" },
    { key:"GD CMH - BT", value: "GD CMH-BT Gran Demanda Con Medicion Horaria Baja Tensión" },
    { key:"GD CMH - MT", value: "GD CMH-MT Gran Demanda Con Medicion Horaria Media Tensión" }
  ];
  constructor(private plantService: PlantsService, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.assetForm = this.formBuilder.group({
      name: ['', Validators.required],
      country: ['', Validators.required],
      city: ['', Validators.required],
      address: ['', Validators.required],
      distribuidora: ['', Validators.required],
      categoria_tarifaria: ['', Validators.required],
      cod_tarifa: ['', Validators.required]
    });
  }

  get f() { return this.assetForm.controls; }

  createAsset() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.assetForm.invalid) {
      return;
    }
     
    this.plantService.createPlant(
      {
        name: this.f.name.value,
        country: this.f.country.value,
        city: this.f.city.value,
        address: this.f.address.value,
        distribuidora: this.f.distribuidora.value,
        categoria_tarifaria: this.f.categoria_tarifaria.value,
        cod_tarifa: this.f.cod_tarifa.value,
        meters_installed: []
      }
    )
    .subscribe(success => {
      if (success) {
        Swal.fire({
          allowOutsideClick: false,
          type: 'success',
          showCancelButton: false,
          title: 'Exito',
          confirmButtonText: 'El registro ha sido guardado'
        }).then((result) => {
          if (result.value) {
            window.location.href="#/plants";
          }
        });
      }
    });
  }


}
