import { Component, OnInit } from "@angular/core";
import { FormControl, FormGroup, Validators } from "@angular/forms";
import { AddAction } from "../../models/add-action.enum";
import { ServiceComm } from "../../services/service-comm.service";
import { DropzoneService } from "../../services/dropzone.service";

@Component({
  selector: "app-new-drop-zone",
  templateUrl: "./new-drop-zone.component.html",
  styleUrls: ["./new-drop-zone.component.css"]
})
export class NewDropZoneComponent implements OnInit {
  public addForm: FormGroup;

  constructor(
    private serviceComm: ServiceComm,
    private dropzoneService: DropzoneService
  ) {
    this.addForm = new FormGroup(
      {
        dzName: new FormControl("", Validators.required),
        gps: new FormControl("x.x,y.y", [
          Validators.required,
          Validators.pattern("d+.d+,d+.d+")
        ]),
        address: new FormControl("", Validators.required),
        website: new FormControl("", Validators.required),
        contactMail: new FormControl("", [
          Validators.required,
          Validators.email
        ]),
        isDz: new FormControl(true),
        isTunnel: new FormControl(false)
      },
      { updateOn: "blur" }
    );
  }

  ngOnInit() {}

  onSubmit(formData) {
    const splitGps: Array<string> = formData.gps.split(",");
    let dzType: Array<string> = new Array<string>();

    if (formData.isDz === true) {
      dzType.push("dz");
    }
    if (formData.isTunnel === true) {
      dzType.push("tunnel");
    }

    this.dropzoneService.AddDropZone(splitGps[0],
                                     splitGps[1],
                                     formData.dzName,
                                     formData.address,
                                     formData.website,
                                     formData.contactMail,
                                     dzType,
                                     false)
                          .subscribe(() => {
                              this.serviceComm.RefreshData(AddAction.Dropzone);
                          });
  }
}
