import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';
declare var swal: any;
@Component({
  selector: 'app-command-window',
  templateUrl: './command-window.component.html',
  styleUrls: ['./command-window.component.scss']
})
export class CommandWindowComponent implements OnInit {
  useridd: any;
  device_type: any;
  CommandArr=[];
  DeviceName: any;
  menuShow:boolean=true;
  immobilizeCount: number;
  errIcon: boolean;
  showErr: boolean=false;
  ImmErrMsg: any;
  shoError: any;
  errorIcon: boolean;

  constructor(public dialogRef: MdDialogRef<CommandWindowComponent>,@Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService) { }

  ngOnInit() {
    this.CommandArr=[];
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    var d_model = this.data.deviceObject.device_model;
    console.log(this.data);
    
    this.DeviceName = this.data.deviceObject.Device_Name; 
    this.contactService.getDeviceModelbyID(d_model).subscribe(res=>{
      console.log('deviceModel=>',res);
      this.device_type = res[0].device_type;
 
    //   sms_ip:{
    //   type:String
    // },
    // sms_apn:{
    //   type:String
    // },
    //  sms_timezone:{
    //   type:Date
    // },
    // sms_loc:{
    //   type:String
    // },
    // sms_param:{
    //   type:String
    // },
    //  sms_reset:{
    //   type:String
    // },
    // image_path:{
    //   type:String
    // },

      if(res[0].location_command){
        var temp = {
          name: "Check Location",
          action: "LOCATION",
          value: res[0].location_command,
          value1: res[0].sms_loc,
        }
        
        this.CommandArr.push(temp);
      }
      if(res[0].reset_command){
        var temp1 = {
          name: "Reset",
          action:"",
          value: res[0].reset_command,
          value1: res[0].sms_reset,
        }
        this.CommandArr.push(temp1);
      }
      if(res[0].resume_command){
        var temp2 = {
          name: "Restore Engine",
          action:"ON",
          value: res[0].resume_command,
          //  value1: res[0].sms_reset,
        }
        this.CommandArr.push(temp2);
      }

    var  tempObj = {
        name: "Stop Engine",
        action :"OFF",
        value: ''
      }
      this.CommandArr.push(tempObj);
    
      tempObj = {
        name: "SOS Number",
        action:"SOSNUMBER",
        value: ''
      }
      this.CommandArr.push(tempObj);

      tempObj = {
        name: "Check Status",
        action:"STATUS",
        value: ''
      }
      this.CommandArr.push(tempObj);

      tempObj = {
        name: "Check Parameters",
        action:"PARAM",
        value: ''
      }
      this.CommandArr.push(tempObj);

      tempObj = {
        name: "Check Settings",
        action:"SETTING",
        value: ''
      }
      this.CommandArr.push(tempObj);

      tempObj = {
        name: "Firmware Version",
        action:"PARAM",
        value: 'FIRMVERSION'
      }
      this.CommandArr.push(tempObj);

      if(res[0].configuration_command){
        var temp3 = {
          name: "Configuration Command",
          action: "CONFIG",
          value: res[0].configuration_command
        }
        this.CommandArr.push(temp3);
        

      }
      if(res[0].immoblizer_command){
        var temp4 = {
          name: "Immobilise Command",
          action:"",
          value: res[0].immoblizer_command
        }
        this.CommandArr.push(temp4);


      }

      var tempObj = {
        name: "More",
        action:"",
        value: 'openWindow'
      }

      this.CommandArr.push(tempObj);
      console.log('this.CommandArr',this.CommandArr);

      console.log(this.data);
      var imei = this.data.deviceObject.Device_ID; 
          console.log('this.device_type',this.device_type);
  
 



    })

  }

  triggerCMd(cmdObj){
    this.errorIcon= false;
    var that =this;
    var pld = {
          cmd: cmdObj.action,
          imei:this.data.deviceObject.Device_ID,
          protocol_type: this.device_type, 
          user : this.data.deviceObject.user
      }
    console.log(cmdObj);
    if(cmdObj.value === 'openWindow'){
      this.dialogRef.close('openOther');
    }else{

  //     $(document).ready(function() {
  // $("#close_account").on("click", function(e) {
    var buttons = $('<div>')
    .append(that.createButton('GPRS Command', function() {
       
      //  console.log('ok');
       that.gpsCommand(pld) 
    })).append(that.createButton('SMS Command', function() {
       swal.close();
       that.smsCommand(cmdObj.value1)
      //  console.log('Later'); 
    })).append(that.createButton('Cancel', function() {
       swal.close();
       console.log('Cancel');
    }));
    
    // e.preventDefault();
    swal({
      title: "Please choose command",
      html: buttons,
      type: "info",
      showConfirmButton: false,
      showCancelButton: false
    });
     
      
    console.log("command triggered",pld);
 
    // this.contactService.triggerCommand1(pld).subscribe(res=>{
    //   console.log('command triggered Response',res);
    //   this.checkCmdstatus(res['_id']);
    //   },err=>{
    //       // this.dialogRef.close('close');  
    //       this.menuShow = !this.menuShow;
    //       console.log(JSON.parse(err['_body']));
    //       var errorMessage = JSON.parse(err['_body']);
    //       that.errorIcon= true;
    //       that.showErr  =  !that.showErr ;
    //       that.ImmErrMsg = errorMessage.message;
    //   })

    }

  }

  smsCommand(s){
    console.log(s);
    
    var pld={
      phone:this.data.deviceObject.sim_number,
      user:this.useridd,
      sentence:s
    }
    this.contactService.post('/notifs/sendMessage',pld).subscribe(res=>{
      console.log('command triggered Response',res);
      // this.checkCmdstatus(res['_id']);
      },err=>{
          // this.dialogRef.close('close');  
          this.menuShow = !this.menuShow;
          console.log(JSON.parse(err['_body']));
          var errorMessage = JSON.parse(err['_body']);
          this.errorIcon= true;
          this.showErr  =  !this.showErr ;
          this.ImmErrMsg = errorMessage.message;
          swal.close();
      })
  }

  gpsCommand(pld){
    this.contactService.triggerCommand1(pld).subscribe(res=>{
      console.log('command triggered Response',res);
      this.checkCmdstatus(res['_id']);
      },err=>{
          // this.dialogRef.close('close');  
          this.menuShow = !this.menuShow;
          console.log(JSON.parse(err['_body']));
          var errorMessage = JSON.parse(err['_body']);
          this.errorIcon= true;
          this.showErr  =  !this.showErr ;
          this.ImmErrMsg = errorMessage.message;
          swal.close();
      })
  }


createButton(text, cb) {
  if(text=="cancel"){
     return $('<button style="background: red;color: white;border-radius: 5px;padding: 7px;margin: 8px; ">' + text + '</button>').on('click', cb);
  }else
  return $('<button style="background: blue;color: white;border-radius: 5px;padding: 7px;margin: 8px; ">' + text + '</button>').on('click', cb);
}
  checkCmdstatus(cmdQId){
    this.menuShow = !this.menuShow;
    this.immobilizeCount = 45; 
    var that=this;
    var timer = setInterval(()=>{
      that.immobilizeCount--
      if( that.immobilizeCount=== 0){
        clearInterval(timer);
        clearInterval(callApi);
        that.errorIcon= true;
        that.showErr  =  !that.showErr ;
        that.ImmErrMsg = "Timeout occured, Please Try again";
      }
    },1000)

    // var stopCalling = setTimeout(()=>{
    //   clearInterval(timer);
    //   clearInterval(callApi);
    //   clearTimeout(stopCalling);

    // },45000)

    var callApi = setInterval(()=>{
      this.contactService.getEngineCutStatus_1(cmdQId).subscribe(res1=>{
        // console.log('res11111111111111111111111111111111111111=>',res1.status);
        if(res1.status == 'SUCCESS'){
          clearInterval(timer);
          clearInterval(callApi);
          that.showErr  =  !that.showErr ;
          // console.log('res11111111111111111111111111111111111111=>',res1)
          that.ImmErrMsg = res1.deviceResponse;
        }       
      },err=>{
        clearInterval(timer);
        clearInterval(callApi);
        that.showErr  =  !that.showErr ;
        that.ImmErrMsg = "Please Try after sometime";
      })
    },4000)
 

  }



  close(){
    this.dialogRef.close('close');
  }
}


