import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import { ContactService } from "../contact.service";
import { Router } from "@angular/router";
import * as XLSX from "xlsx";

declare var $: any;

@Component({
  selector: "app-virtual-device",
  templateUrl: "./virtual-device.component.html",
  styleUrls: ["./virtual-device.component.scss"],
})
export class VirtualDeviceComponent implements OnInit {
  errorMsg = "";
  showError;
  arrayBuffer: any;
  file: File;
  submittedList = [];
  virtualDevice = {
    imei: "",
    port: "",
    host: "",
    model: "",
    route: [],
  };
  tabelObj: any;
  useridd: any;
  superAdmin: any;
  custtype: any;
  orgChek: any;
  supAdminDropDown = false;

  distributerValue;
  dealerValue;
  @ViewChild("fileInput")

  // this InputVar is a reference to our input.
  InputVar: ElementRef;
  constructor(private contactService: ContactService, private router: Router) {}

  selectedItems = [];
  resetData() {
    this.InputVar.nativeElement.value = "";
    this.errorMsg = "";
    this.file = null;
    this.virtualDevice = {
      imei: "",
      port: "",
      host: "",
      model: "",
      route: [],
    };
  }
  ngOnInit() {
    if (this.orgChek === true) {
      this.supAdminDropDown = true;
    }
    // this.loadropdown();

    var that = this;
  }

  onChange(event) {
    this.file = event.target.files[0];
  }
  onUpload() {
    this.showError = false;
    if (this.file) {
      this.realExcelData();
    } else {
      this.showError = true;
      this.errorMsg = "Please select file";
    }
  }
  realExcelData() {
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      this.arrayBuffer = fileReader.result;
      var data = new Uint8Array(this.arrayBuffer);
      var arr = new Array();
      for (var i = 0; i != data.length; ++i)
        arr[i] = String.fromCharCode(data[i]);
      var bstr = arr.join("");
      var workbook = XLSX.read(bstr, { type: "binary" });
      var first_sheet_name = workbook.SheetNames[0];
      var worksheet = workbook.Sheets[first_sheet_name];
      this.setDataToAPI(XLSX.utils.sheet_to_json(worksheet, { raw: true }));
    };
    fileReader.readAsArrayBuffer(this.file);
  }
  setDataToAPI(data) {
    console.log(data);
    let newData = [];
    if (data.length) {
      data = data.forEach((d) => {
        if (d.Lattitude && d.Longitude) {
          newData.push({
            lat: d.Lattitude,
            lng: d.Longitude,
          });
        }
      });
    }
    this.virtualDevice.route = newData;
    this.submit(this.virtualDevice);
  }
  successMesssage = "";
  submit(virtualDevice, isAdd = true) {
    this.successMesssage = "";
    if (!virtualDevice.route.length) {
      this.errorMsg = "Please Upload Lat/long";
    } else if (!virtualDevice.host) {
      this.errorMsg = "Please enter Host";
    } else if (!virtualDevice.imei) {
      this.errorMsg = "Please enter IMEI";
    } else if (!virtualDevice.port) {
      this.errorMsg = "Please enter port";
    } else if (!virtualDevice.model) {
      this.errorMsg = "Please enter model";
    } else {
      let postObj = Object.assign({}, virtualDevice);
      if (isAdd) {
        this.submittedList.unshift(postObj);
      }
      this.contactService.post("/virtualDevice", postObj, false).subscribe(
        (resp) => {
          this.resetData();
          this.successMesssage = "Data uploaded successfully";
          console.log(resp);
        },
        (err) => {
          this.errorMsg = "Request Failed";
        }
      );
    }
  }
}
