import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-add-device',
  templateUrl: './add-device.component.html',
  styleUrls: ['./add-device.component.scss']
})
export class AddDeviceComponent implements OnInit {
  errmsg:any='';
  device_license:any='Yearly';
  device_id:any;
  device_name:any;
  device_sim:any;
  licenseArr=['Yearly','Lifetime'];
  modelArr=[];
  vehicleArr=[];
  modelId:any;
  vtypeId:any;
  useridd: any;
  superAdmin: any;
  emailid: any;
  sup_admin: any;
  custId: string;
  custtype: any;
  DealerId: any;
  cust: boolean;
  createdby: any;
  dealerid: any;
  owner: any;
  errorIcon: boolean=false;
  ImmErrMsg: string;
  constructor(public dialogRef: MdDialogRef<AddDeviceComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,private _flashMessagesService: FlashMessagesService,) { 

    }

  ngOnInit() {
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;  
    if(this.superAdmin){
      this.sup_admin = this.useridd;
    }

    this.custId = localStorage.getItem('custId');
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.DealerId =  JSON.parse(window.atob(window.localStorage.Dealer_token.split(".")[1]))._id;  
    console.log("DealerID",this.DealerId) 
    var accountToggle ;
    var sat =localStorage.getItem('superadmin') ;
    var ddt =localStorage.getItem('Dealer') ;
    var cst = localStorage.getItem('Custumer');
    var d =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer_ID;
    console.log('sat,ddt,cst',sat,ddt,cst);
    if((sat === 'ON')&&(ddt=== 'ON')&&(cst === 'ON')){
      this.dealerid= d._id;
      this.owner = d._id;
    }
    if((sat === 'ON')&&(ddt=== 'ON')&&(cst === 'OFF')){
            this.dealerid= this.useridd;
            this.owner = this.sup_admin;

    }

    if((sat === 'OFF')&&(ddt=== 'ON')&&(cst === 'OFF')){
            this.dealerid=  this.sup_admin;
            this.owner = this.sup_admin;
    }

 
   this.getDeviceModel();
    this.getvehDetail();
    

  }

  add(){
    console.log();
    if((this.device_id === undefined)||(this.device_name === undefined)||(this.device_sim === undefined)||(this.modelId === undefined)||(this.vtypeId === undefined)){
      // this._flashMessagesService.show('Please fill all mendatory field', { cssClass: 'alert-danger', timeout: 3000 });
      var that = this ;

      var timeOutVal = setTimeout(()=>{
        console.log('inside tout');
        that.errorIcon = false;
        that.ImmErrMsg = "";
        clearTimeout(timeOutVal);
      },3000)
      this.errorIcon = true;
      this.ImmErrMsg = "Please fill all mendatory field";
    }else{
      var ed = new Date();
      var newDevice = {
        devicename: this.device_name,
        deviceid: this.device_id,
        model: this.modelId,
        typdev: "Tracker",
        emailid: this.emailid,
        Mileage : "10",
        sim_number: this.device_sim,
        created_by: this.owner,
        Dealer :  this.dealerid,
        vehicleType :  this.vtypeId,
        supAdmin: this.sup_admin,
        device_model: this.modelId,
        expdate: ed.setFullYear(ed.getFullYear()+1),
        License : this.device_license,
        user : this.useridd  
      }
      console.log(newDevice);
      this.contactService.addDevice(newDevice)
      .subscribe((device) => {
        this.dialogRef.close('added')
      },err=>{
        if (err.status == 400) {

          var that = this ;

          var timeOutVal = setTimeout(()=>{
            console.log('inside tout');
            that.errorIcon = false;
            that.ImmErrMsg = "";
            clearTimeout(timeOutVal);
          },3000)
          // this._flashMessagesService.show('The Device ID already exists in our system.', { cssClass: 'alert-danger', timeout: 3000 });
          this.errorIcon = true;
          this.ImmErrMsg = "The Device ID already exists in our system.";
        }else{

          var that = this ;

          var timeOutVal = setTimeout(()=>{
            console.log('inside tout');
            that.errorIcon = false;
            that.ImmErrMsg = "";
            clearTimeout(timeOutVal);
          },3000)
            // this._flashMessagesService.show('Internal server error', { cssClass: 'alert-danger', timeout: 3000 });
            this.errorIcon = true;
            this.ImmErrMsg = "Internal server error";
        }
      })


      
      // if (this.custtype) {
      //   newDevice['Dealer'] = this.useridd;
      // } else {
      //   newDevice['Dealer'] = this.DealerId
      // }
   



    }
  }

  close(){
    // this._flashMessagesService.hide()
  
    this.dialogRef.close();
  }

  getDeviceModel() {
    this.contactService.getDevModel()
      .subscribe(res => {
        this.modelArr=[];
        this.modelArr = res;
        var devname = [];
      
        for(var i = 0 ; i<this.modelArr.length;i++){
          var modelName;        
          if(this.modelArr[i].deviceport != undefined){
            modelName = this.modelArr[i].device_type + " " + "(Port : " + this.modelArr[i].deviceport + ")";   
          }else{
            modelName = this.modelArr[i].device_type;
          }
          this.modelArr[i]['modelName']= modelName;
        }
        console.log(devname);
      })
  }


  getvehDetail(){
    this.contactService.getvehType(this.useridd)
      .subscribe(res=>{
        this.vehicleArr=res;
        var vdata = res;
        for(var a = 0;a<this.vehicleArr.length;a++){
            var vehtypename = vdata[a].brand + " " + vdata[a].model;
            this.vehicleArr[a].vehicle_name = vehtypename;
        }
         console.log("allveh",this.vehicleArr);
      })
  }

}
