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

@Component({
  selector: 'app-expense-component',
  templateUrl: './expense-component.component.html',
  styleUrls: ['./expense-component.component.scss']
})
export class ExpenseComponentComponent implements OnInit {
  expenseVal :any;
  expenseTotal:number=0;
  expenseType=[
   { "value" : "FOOD EXP.", "viewValue" : "FOOD EXP." },
   { "value" : "POLICE/TRO", "viewValue" : "POLICE/TRO" }, 
   { "value" : "PETTA", "viewValue" : "PETTA" }, 
   { "value" : "TELEPHONE", "viewValue" : "TELEPHONE" },
    { "value" : "TOLE", "viewValue" : "TOLE" }, 
   { "value" : "TRAVELLING", "viewValue" : "TRAVELLING" }, 
   { "value" : "MISCE EXP.", "viewValue" : "MISCE EXP." } ,
   { "value" : "FUEL", "viewValue" : "FUEL" } ,
   { "value" : "TYRE", "viewValue" : "TYRE" } ,
   { "value" : "WORKSHOP", "viewValue" : "WORKSHOP" } ,
   { "value" : "SPARES", "viewValue" : "SPARES" } ,
   { "value" : "ROOMRENT", "viewValue" : "ROOMRENT" } ,
   { "value" : "PERMIT", "viewValue" : "PERMIT" } ,
   { "value" : "DONATION", "viewValue" : "DONATION" } 
  ];
  paymentMethod = [
    {"value": "CASH","viewValue":"CASH"},
    {"value": "CHEQUE","viewValue":"CHEQUE"},
    {"value": "ONLINE","viewValue":"ONLINE"},
    {"value": "OTHER","viewValue":"OTHER"}
  ]
  
prepaymentVal:any
  tripPayload: any;
  expenseArr: any=[];
  Load: boolean=false;
  errorMsg: string;
  constructor(public dialogRef: MdDialogRef<ExpenseComponentComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,) { 
     
      this.tripPayload = data;
      console.log('this.tripPayload',this.tripPayload);
    }

  ngOnInit() {
    this.expenseArr = [];
    this.getExpense(this.tripPayload._id);
    this.getCurrencies();
  }


  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);
  }


  currency = [];
  optiondefault:any;
  getCurrencies(){
    this.currency = [];
    // this.contactService.getCurrencies().subscribe(res=>{   
      var currencyObj = this.currencyJson;  
        console.log('currencyObj',currencyObj);
      for(var i in currencyObj){
        if(this.data.currency != undefined){
          var devicecurr = this.data.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);
      // this.loadropdown();
    // })
  }

  totalExpense:any;
  showTable : boolean = true;

  saveExpense(){
    let that = this;
    if(this.totalExpense == undefined){
      this.errorMsg = "Amount is required";
      this.showError = true;
      var error =  setTimeout(function(){
        that.showError = false; 
        
        clearInterval(error);
      },5000)

    }else{
      var expensePayload ={
        "user": this.tripPayload.user,
        "currency":this.optiondefault.split('-')[0],
         "vehicle": this.tripPayload.deviceObjId,
         "payment_mode":this.prepaymentVal,
         "amount":this.totalExpense,
         "odometer":this.tripPayload.total_odo,
         "type":this.expenseVal,
         "trip" : this.tripPayload._id,
         "date": new Date().toISOString(),
      }
  
      console.log('expensePayload=>',expensePayload);
      this.contactService.saveExpense(expensePayload).subscribe(res=>{
        console.log(res);
    
        if(res.message=="added Successfully"){
          this.errorMsg = "Trip expense added !";
          this.showError = true;
          var error =  setTimeout(function(){
            that.showError = false; 
       
            clearInterval(error);
          },5000)
       
          this.getExpense(this.tripPayload._id);
  
         
          // this.dialogRef.close('success');
        }
      },err=>{
        console.log(err);
      })
  
    }


  }
  showError :boolean=false;
  
  getExpense(tripid){

    let that = this;
    this.Load   = true;
    this.contactService.getExpense(tripid).subscribe(res=>{
      this.Load= false;
      this.showTable = true;
      console.log("response=>",res);
     var eArr = res;
  
      if(eArr.length == 0){
          console.log("no expense");
          this.expenseTotal = 0;
      }else{
        this.expenseArr = res;
        this.addAmount(this.expenseArr);
      }

    },err=>{
      this.Load= false;
      console.log("inside no expense block")
      this.showTable = false;
      this.showError = true;
      this.errorMsg = "No Expence record found";
      this.expenseTotal = 0;
      // this.getExpense(tripid);
    
      this.expenseArr = [];
      var error =  setTimeout(function(){  
        that.showError = false; 
        clearInterval(error);
      },5000)

    })
  }

  delete(listObj){
    this.contactService.deleteExpense(listObj._id).subscribe(res=>{
      console.log(res);
     let tid =  this.tripPayload._id
      this.getExpense(tid);
    })

  }

  addAmount(amountArr){
    console.log('amountArr',amountArr);
    this.expenseTotal = 0;
    if(amountArr.length != 0){  
      var expenseSum =0;
      for(var i = 0 ;i<amountArr.length;i++){
        expenseSum = amountArr[i].amount?parseFloat(amountArr[i].amount):0;
        this.expenseTotal +=  expenseSum ;
      }
    }

  }


  cancel(){
    this.dialogRef.close('cancel');
  }
  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"
  }

}
