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

declare var $:any;

@Component({
  selector: 'app-general-settings',
  templateUrl: './general-settings.component.html',
  styleUrls: ['./general-settings.component.scss']
})
export class GeneralSettingsComponent implements OnInit {
  errorMsg:any;
  virtualAcc
  showError : boolean=false;
  igndtection = ['ACC','MOVEMENT'];
  dInput = ['ACC','AC','DOOR'];
  aInput = ['Fuel', 'Tempreture','Battey Status'];
  fuelmeasObj  = ['GPS','MANUAL'];
  tripType = [{view : 'One WAY',value : 1},{view : 'Two Way', value : 2}]
  tripTypeVal:any

  loader :boolean = true;
  generalSetings: FormGroup;
  devicesss: any;
  custtype: any;
  useridd: any;
  mb: any;
  emailid: any;
  superAdmin: any;
  finall: any;
  options: any=[];
  deviceArr: any =[];
  currencyValue: any;
  id: any;
  driverManagement:boolean=false;
  selected_ac_wire="Forward"
  ac_wire_setting=['Forward','Reversed']
  constructor(public dialogRef: MdDialogRef<GeneralSettingsComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,public formBuilder: FormBuilder,private _flashMessagesService: FlashMessagesService) { 
      console.log('this.data.device',this.data.device);
      this.id = this.data.device._id ;
      this.driverManagement=data.device.user.driverManagement?data.device.user.driverManagement:false
      console.log('this.id=>',this.id)
      var flmsrmnt;
      if(this.data.device.fuelMeasurement){
        if(this.data.device.fuelMeasurement == 'GPS'){
          flmsrmnt = this.fuelmeasObj[0];
        }
        if(this.data.device.fuelMeasurement == 'MANUAL'){
          flmsrmnt = this.fuelmeasObj[1];
        }
        
      }

      this.tripTypeVal = this.data.device?this.data.device.tripType :1 ; 
      this.virtualAcc=this.data.device.virtualacc?this.data.device.virtualacc:false;
      this.selected_ac_wire=this.data.device.ac_wire_setting?this.data.device.ac_wire_setting:'Forward'
      this.generalSetings = formBuilder.group({
        driver_name : [this.data.device.driver_name?this.data.device.driver_name : ''],
        devicename : [this.data.device.Device_Name?this.data.device.Device_Name : ''],
        driver_number : [this.data.device.contact_number?this.data.device.contact_number : null],
        total_odo: [this.data.device.total_odo?this.data.device.total_odo : 0],
        speed: [this.data.device.SpeedLimit?this.data.device.SpeedLimit : 60],
        mileage: [this.data.device.Mileage?this.data.device.Mileage : 10],
        ignDetection:[this.data.device.ignitionSource?this.data.device.ignitionSource : this.igndtection[0]],
        digitalInput : [this.data.device.digitalInput?this.data.device.digitalInput:this.dInput[0]],
        analogInput:[this.data.device.analogInput?this.data.device.analogInput:this.aInput[0]],
        fuelMeasurment : [flmsrmnt],
        overStoppedLimit:[this.data.device.overStoppedLimit?this.data.device.overStoppedLimit : 0],
        overIdleLimit:[this.data.device.overIdleLimit?this.data.device.overIdleLimit : 0],
        currencyVlaue : [this.currencyValue],
        
      })

      // $('select').hide();
    
   
    }
    option:any;
  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.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.getCurrencies();  
    if(this.driverManagement)
    this.getDrivers()
  }
  drivers
  getDrivers(){
    this.contactService.get("/driver/getDrivers?userid="+this.useridd).subscribe(res=>{
      this.drivers=res
    })
  }


  dataSelect=[];
  filterStates(val) {
    console.log(val)
    // console.log(this.dummyuserData)

    if (val) {
      const filterValue: any = val;
      console.log(this.currency);
      this.dataSelect = this.currency.filter(function (d) {
              console.log("inside Search Method=>",d);
        return d.country.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;
      });
      return this.dataSelect;
    }
    // console.log("searched user=>",this.dataSelect);
  }

  // loadropdown() {
  //   let that = this;
  //   var script = document.createElement("script");
  //   script.setAttribute("type", "text/javascript");
  //   script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  //   document.getElementsByTagName("head")[0].appendChild(script);
  //   setTimeout(() => {
  //     $('select').multipleSelect({
  //       single: true,
  //       width: 200,
  //       placeholder: 'Select Currency.....',
  //       filter: true,
    
      
  //     })
    

  //   }, 100);

  // }

  



  ngOnDestroy(){
   
    this.dialogRef.close('cancelled');
  }
  currencyArr = [];
  saveDetail(){
 
    if(this.dataSelect.length == 0){
        console.log("currency",(this.optiondefault).split('-')[0]);
        var currencyyy = this.optiondefault.split('-')[0];
    }else{
      console.log(this.dataSelect[0].currencyVal);
      var currencyyy  = this.dataSelect[0].currencyVal ;
    }
    console.log(this.generalSetings.value);
    // this.currencyArr =$('#select').multipleSelect('getSelects','value');
    // if(this.currencyArr.length != 0){
    //   var temp = this.currencyArr[0].split(':')[1]; 
    //   this.generalSetings.value.currencyVlaue = temp.split("'")[1];
    // }  
    
      var devSettingObj = {    
        speed: this.generalSetings.value.speed,
        Mileage: this.generalSetings.value.mileage,
        ignDetection:this.generalSetings.value.ignDetection,
        digitalInput : this.generalSetings.value.digitalInput,
        analogInput:this.generalSetings.value.analogInput,
        fuelMeasurement :this.generalSetings.value.fuelMeasurment,
        currency : currencyyy,
        device_model:this.data.device.device_model._id,
        overStoppedLimit:this.generalSetings.value.overStoppedLimit,
        overIdleLimit:this.generalSetings.value.overIdleLimit,
        _id : this.id
      }
          console.log(this.option);
      if(this.virtualAcc != undefined){
            devSettingObj['virtualacc'] = this.virtualAcc ;

          }
          if(this.tripTypeVal != undefined){
            devSettingObj['tripType'] = this.tripTypeVal ;

          }
      // if((this.generalSetings.value.currencyVlaue != null)||(this.generalSetings.value.currencyVlaue != undefined)){
      //   devSettingObj['currency'] = this.generalSetings.value.currencyVlaue;
      // }
      if(this.generalSetings.value.total_odo !=null){
        devSettingObj['total_odo'] = this.generalSetings.value.total_odo;
      }
      if(this.selected_ac_wire){
        devSettingObj['ac_wire_setting'] = this.selected_ac_wire;
      }

      if(this.generalSetings.value.driver_name !=null){
        devSettingObj['drname'] = this.generalSetings.value.driver_name;
      }

      if(this.generalSetings.value.devicename !=null){
        devSettingObj['devicename'] = this.generalSetings.value.devicename;
      }

      if(this.generalSetings.value.driver_number !=null){
        devSettingObj['dphone'] = this.generalSetings.value.driver_number;
      }

      console.log('devSettingObj',devSettingObj);
      this.contactService.editdevice(devSettingObj).subscribe(res=>{

        this.dialogRef.close('done');

      },err=>{
        this.showError=true;
        this.errorMsg= "Couldn't save Information, pLease try after sometime";
        this._flashMessagesService.show(this.errorMsg, { cssClass: 'alert-danger', timeout: 3000});
      })
     
    
    
     
  }

  closebox(){
    console.log('close');
    this.dialogRef.close('cancelled');
  }
  currency = [];
  optiondefault:any;
  getCurrencies(){
    this.currency = [];
    // this.contactService.getCurrencies().subscribe(res=>{
      var currencyObj = this.currencyJson;  
      for(var i in currencyObj){
        if(this.data.device.currency != undefined){
          var devicecurr = this.data.device.currency ; 
          if(i == devicecurr){    
            this.optiondefault = i+ '-' +  currencyObj[i];
           }

        }else{
          if(i == 'INR'){    
            this.optiondefault = i+ '-' +  currencyObj[i];
           }
        }
    
      var tempObj = {
        currencyVal : i,
        country       : i+ '-' +  currencyObj[i]
      }
        this.currency.push(tempObj);
      }
    
      console.log(this.currency);
     
  }

  setContactNumber(){
    console.log(this.generalSetings.value.driver_name);
    for(var i=0;i<this.drivers.length;i++){
      if(this.drivers[i].name==this.generalSetings.value.driver_name){
        this.generalSetings.patchValue({
          driver_number:Number(this.drivers[i].contactNumber)
        })
      }
    }
   
    
  }

  currencyJson = {
    "AED": "United Arab Emirates Dirham",
    "AFN": "Afghan Afghani",
    "ALL": "Albanian Lek",
    "AMD": "Armenian Dram",
    "ANG": "Netherlands Antillean Guilder",
    "AOA": "Angolan Kwanza",
    "ARS": "Argentine Peso",
    "AUD": "Australian Dollar",
    "AWG": "Aruban Florin",
    "AZN": "Azerbaijani Manat",
    "BAM": "Bosnia-Herzegovina Convertible Mark",
    "BBD": "Barbadian Dollar",
    "BDT": "Bangladeshi Taka",
    "BGN": "Bulgarian Lev",
    "BHD": "Bahraini Dinar",
    "BIF": "Burundian Franc",
    "BMD": "Bermudan Dollar",
    "BND": "Brunei Dollar",
    "BOB": "Bolivian Boliviano",
    "BRL": "Brazilian Real",
    "BSD": "Bahamian Dollar",
    "BTC": "Bitcoin",
    "BTN": "Bhutanese Ngultrum",
    "BWP": "Botswanan Pula",
    "BYN": "Belarusian Ruble",
    "BZD": "Belize Dollar",
    "CAD": "Canadian Dollar",
    "CDF": "Congolese Franc",
    "CHF": "Swiss Franc",
    "CLF": "Chilean Unit of Account (UF)",
    "CLP": "Chilean Peso",
    "CNH": "Chinese Yuan (Offshore)",
    "CNY": "Chinese Yuan",
    "COP": "Colombian Peso",
    "CRC": "Costa Rican Colón",
    "CUC": "Cuban Convertible Peso",
    "CUP": "Cuban Peso",
    "CVE": "Cape Verdean Escudo",
    "CZK": "Czech Republic Koruna",
    "DJF": "Djiboutian Franc",
    "DKK": "Danish Krone",
    "DOP": "Dominican Peso",
    "DZD": "Algerian Dinar",
    "EGP": "Egyptian Pound",
    "ERN": "Eritrean Nakfa",
    "ETB": "Ethiopian Birr",
    "EUR": "Euro",
    "FJD": "Fijian Dollar",
    "FKP": "Falkland Islands Pound",
    "GBP": "British Pound Sterling",
    "GEL": "Georgian Lari",
    "GGP": "Guernsey Pound",
    "GHS": "Ghanaian Cedi",
    "GIP": "Gibraltar Pound",
    "GMD": "Gambian Dalasi",
    "GNF": "Guinean Franc",
    "GTQ": "Guatemalan Quetzal",
    "GYD": "Guyanaese Dollar",
    "HKD": "Hong Kong Dollar",
    "HNL": "Honduran Lempira",
    "HRK": "Croatian Kuna",
    "HTG": "Haitian Gourde",
    "HUF": "Hungarian Forint",
    "IDR": "Indonesian Rupiah",
    "ILS": "Israeli New Sheqel",
    "IMP": "Manx pound",
    "INR": "Indian Rupee",
    "IQD": "Iraqi Dinar",
    "IRR": "Iranian Rial",
    "ISK": "Icelandic Króna",
    "JEP": "Jersey Pound",
    "JMD": "Jamaican Dollar",
    "JOD": "Jordanian Dinar",
    "JPY": "Japanese Yen",
    "KES": "Kenyan Shilling",
    "KGS": "Kyrgystani Som",
    "KHR": "Cambodian Riel",
    "KMF": "Comorian Franc",
    "KPW": "North Korean Won",
    "KRW": "South Korean Won",
    "KWD": "Kuwaiti Dinar",
    "KYD": "Cayman Islands Dollar",
    "KZT": "Kazakhstani Tenge",
    "LAK": "Laotian Kip",
    "LBP": "Lebanese Pound",
    "LKR": "Sri Lankan Rupee",
    "LRD": "Liberian Dollar",
    "LSL": "Lesotho Loti",
    "LYD": "Libyan Dinar",
    "MAD": "Moroccan Dirham",
    "MDL": "Moldovan Leu",
    "MGA": "Malagasy Ariary",
    "MKD": "Macedonian Denar",
    "MMK": "Myanma Kyat",
    "MNT": "Mongolian Tugrik",
    "MOP": "Macanese Pataca",
    "MRO": "Mauritanian Ouguiya (pre-2018)",
    "MRU": "Mauritanian Ouguiya",
    "MUR": "Mauritian Rupee",
    "MVR": "Maldivian Rufiyaa",
    "MWK": "Malawian Kwacha",
    "MXN": "Mexican Peso",
    "MYR": "Malaysian Ringgit",
    "MZN": "Mozambican Metical",
    "NAD": "Namibian Dollar",
    "NGN": "Nigerian Naira",
    "NIO": "Nicaraguan Córdoba",
    "NOK": "Norwegian Krone",
    "NPR": "Nepalese Rupee",
    "NZD": "New Zealand Dollar",
    "OMR": "Omani Rial",
    "PAB": "Panamanian Balboa",
    "PEN": "Peruvian Nuevo Sol",
    "PGK": "Papua New Guinean Kina",
    "PHP": "Philippine Peso",
    "PKR": "Pakistani Rupee",
    "PLN": "Polish Zloty",
    "PYG": "Paraguayan Guarani",
    "QAR": "Qatari Rial",
    "RON": "Romanian Leu",
    "RSD": "Serbian Dinar",
    "RUB": "Russian Ruble",
    "RWF": "Rwandan Franc",
    "SAR": "Saudi Riyal",
    "SBD": "Solomon Islands Dollar",
    "SCR": "Seychellois Rupee",
    "SDG": "Sudanese Pound",
    "SEK": "Swedish Krona",
    "SGD": "Singapore Dollar",
    "SHP": "Saint Helena Pound",
    "SLL": "Sierra Leonean Leone",
    "SOS": "Somali Shilling",
    "SRD": "Surinamese Dollar",
    "SSP": "South Sudanese Pound",
    "STD": "São Tomé and Príncipe Dobra (pre-2018)",
    "STN": "São Tomé and Príncipe Dobra",
    "SVC": "Salvadoran Colón",
    "SYP": "Syrian Pound",
    "SZL": "Swazi Lilangeni",
    "THB": "Thai Baht",
    "TJS": "Tajikistani Somoni",
    "TMT": "Turkmenistani Manat",
    "TND": "Tunisian Dinar",
    "TOP": "Tongan Pa'anga",
    "TRY": "Turkish Lira",
    "TTD": "Trinidad and Tobago Dollar",
    "TWD": "New Taiwan Dollar",
    "TZS": "Tanzanian Shilling",
    "UAH": "Ukrainian Hryvnia",
    "UGX": "Ugandan Shilling",
    "USD": "United States Dollar",
    "UYU": "Uruguayan Peso",
    "UZS": "Uzbekistan Som",
    "VEF": "Venezuelan Bolívar Fuerte (Old)",
    "VES": "Venezuelan Bolívar Soberano",
    "VND": "Vietnamese Dong",
    "VUV": "Vanuatu Vatu",
    "WST": "Samoan Tala",
    "XAF": "CFA Franc BEAC",
    "XAG": "Silver Ounce",
    "XAU": "Gold Ounce",
    "XCD": "East Caribbean Dollar",
    "XDR": "Special Drawing Rights",
    "XOF": "CFA Franc BCEAO",
    "XPD": "Palladium Ounce",
    "XPF": "CFP Franc",
    "XPT": "Platinum Ounce",
    "YER": "Yemeni Rial",
    "ZAR": "South African Rand",
    "ZMW": "Zambian Kwacha",
    "ZWL": "Zimbabwean Dollar"
  }
}
