import { Component, Inject, Input, OnInit } from "@angular/core";
import { FormGroup } from "@angular/forms";

import {
  MdDialog,
  MdDialogRef,
  MD_DIALOG_DATA,
  MdTabChangeEvent,
} from "@angular/material";
import { ContactService } from "../contact.service";

@Component({
  selector: "app-raw-data-command",
  templateUrl: "./raw-data-command.component.html",
  styleUrls: ["./raw-data-command.component.scss"],
})
export class RawDataCommandComponent implements OnInit {
  injectedData: any;
  useridd: any;
  errFlag: boolean = false;
  errmsg: any = "";
  command: any = "";
  action: any;
  device_type: any;
  imei: any;
  ip: any;
  port: any;
  protocol_type: any;
  constructor(
    public dialogRef: MdDialogRef<RawDataCommandComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,
    private contactService: ContactService
  ) {
    this.injectedData = data;
    console.log("raw data dialog=>", this.injectedData);
  }
  dropdownList: any = [
    { key: "RDM-019", value: "RDM", flag: true, url: "login.itrack.biz" },
    { key: "NIPPON", value: "NIPPON", flag: true, url: "nipponsecura.in" },
    {
      key: "MOTOCARTE",
      value: "MOTOCARTE",
      flag: true,
      url: "login.motocarte.in",
    },
  ];
  ngOnInit() {
    this.dropdownList = this.dropdownList.map((d) => {
      if (
        location.host.match(RegExp(d.url, "g")) != null ||
        location.host.match(RegExp("oneqlik.in", "g")) != null ||
        location.host.match(RegExp("localhost:5200", "g")) != null
      ) {
        d.flag = true;
      } else {
        d.flag = false;
      }
      return d;
    });
    this.useridd = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._id;
    // var d_model = this.data.deviceObject.device_model;
    // this.contactService.getDeviceModelbyID(d_model._id ? d_model._id : d_model).subscribe(res => {
    //   console.log('deviceModel=>', res);
    //   this.device_type = res[0].device_type;
    // })
    this.imei = this.injectedData.deviceObject.imei;
    this.ip = this.injectedData.deviceObject.ip;
    this.port = this.injectedData.deviceObject.port;
  }

  triggerCommand() {
    console.log(this.injectedData);
    var pld = {
      command: this.command,
      protocol_type: this.protocol_type,
      action: "Custom",
      imei: this.imei,
      user: this.useridd,
      ip: this.ip,
      port: this.port,
    };
    console.log("command triggered", pld);
    this.contactService.triggerCommand2(pld).subscribe((res) => {
      console.log(res);
      this.dialogRef.close("success");
    });
    this.closeModal();
  }
  closeModal(): void {
    this.dialogRef.close();
  }

  selectProtocoltype(val: any) {
    this.protocol_type = val;
  }
}
