import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MdSnackBar } from '@angular/material';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { BsDatepickerConfig } from 'ngx-bootstrap';

@Component({
  selector: 'app-device-entry',
  templateUrl: './device-entry.component.html',
  styleUrls: ['./device-entry.component.scss']
})
export class DeviceEntryComponent implements OnInit {
  Inventory: FormGroup;
  today_date = new Date();
  colorTheme = 'theme-dark-blue';

  bsConfig: Partial<BsDatepickerConfig>;
  vhStatus = ['Tagged','Untagged'];
  tracking_software = ['Yes','No'];
  vstattt :any;
  supAdminId: any;
  userid: any;
  DealerName: any;
  InvantoryObject :any;
  buttonToggle:boolean =false;
  objectID: any;
  dataDevModel: any[];
  deviceModel:any;
  DeviceModelValue: any;
  constructor(
    public formBuilder: FormBuilder,public snackBar: MdSnackBar,public contactService: ContactService, private router: Router,
  ) {

    
    this.Inventory = formBuilder.group({
      systemDate : [this.today_date,Validators.required],
      Device_ID: ['',Validators.required],
      Device_Name: ['', Validators.required],
      chessisNumber : ['',Validators.required],
      sim_number_1 : ['',Validators.required],
      sim_provider_1 : ['IDEA'],
      sim_number_2 : [''],
      sim_provider_2 : ['BSNL'],
      approvingRTO : [''],
      ownerNumber : ['',Validators.required],
      Alternatenumber : [''],
      email : [''],
      costumer_first_name : ['',Validators.required],
      costumer_last_name : [''],
      status:[this.vhStatus[1]],
      trackingSoft : [this.tracking_software[1]],
      dealerName :[''],
      engine_number:['']
    })

    this.InvantoryObject = localStorage.getItem('invantoryObject');
    if(this.InvantoryObject){
       var parsedValue =  JSON.parse(this.InvantoryObject);
      this.buttonToggle =true;
      this.objectID = parsedValue._id;
     
      console.log(parsedValue);
        var datetoedit = new Date(parsedValue.systemDate);
        this.Inventory = formBuilder.group({
        systemDate : [datetoedit,Validators.required],
        Device_ID: [parsedValue.Device_ID,Validators.required],
        Device_Name: [parsedValue.Device_Name, Validators.required],
        chessisNumber : [parsedValue.chessisNumber,Validators.required],
        sim_number_1 : [parsedValue.sim_number_1,Validators.required],
        sim_provider_1 : [parsedValue.sim_provider_1],
        sim_number_2 : [parsedValue.sim_number_2],
        sim_provider_2 : [parsedValue.sim_provider_2],
        approvingRTO : [parsedValue.approvingRTO],
        ownerNumber : [parsedValue.ownerNumber,Validators.required],
        Alternatenumber : [parsedValue.Alternatenumber],
        email : [parsedValue.email],
        costumer_first_name : [parsedValue.costumer_first_name,Validators.required],
        costumer_last_name : [parsedValue.costumer_last_name],
        status:[parsedValue.status],
        trackingSoft : [parsedValue.trackingSoft],
        dealerName :[parsedValue.dealerName],
        engine_number:[parsedValue.engine_number]
      })
      if(parsedValue.device_model != undefined){
        this.deviceModel = parsedValue.device_model.device_type;
      }
   
    }
   }

  ngOnInit() {
   var supAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
   this.userid = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
   if(supAdmin == true){
    this.supAdminId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
   }else{
     this.supAdminId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;

   }
   console.log(supAdmin);
    this.dealerData();
    this.getDeviceModel()
  } 


  submitData(){
    console.log('this.Inventory.value',this.dataDevModel);
    
   console.log(JSON.stringify(this.Inventory.value.Device_ID).length);
   if(this.Inventory.invalid){
    let message1="Please fill all required filled";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,
      
    });  

  }
   else if(JSON.stringify(this.Inventory.value.Device_ID).length != 15){
    let message1="Device Id must be of 15 digit";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,
      
    });  

   }
   else{
      // submitData
      this.Inventory.value.operator_id  = this.userid;
      this.Inventory.value.superAdmin = this.supAdminId;
      this.Inventory.value.device_model = this.dataDevModel[0]._id;
      this.contactService.saveDevInventory(this.Inventory.value).subscribe(res=>{
        console.log(res);
        console.log(res.message)
        let message1=res.message;
        let action:any;
        this.snackBar.open(message1, action, {
          duration: 5000,        
        });  
        this.router.navigateByUrl("Inventorylist");
      },err=>{
        console.log(err);
        let message1=JSON.parse(err._body).message;
        let action:any;
        this.snackBar.open(message1, action, {
          duration: 5000,
          
        });  
  
      })
    }
  }

  dealerData(){
    this.contactService.getDealersDetails(this.supAdminId).subscribe(res=>{
      console.log(res);
      this.DealerName = res;
    },err=>{
      console.log(err);
    })

  }
 
  ngOnDestroy(){
    localStorage.removeItem('invantoryObject');
  }

  updateData(){
    console.log('updateData');
    console.log(this.Inventory.value);
   
    if(this.Inventory.invalid){
      let message1="Please fill all required filled";
      let action:any;
      this.snackBar.open(message1, action, {
        duration: 5000,
        
      });  

    } else if(JSON.stringify(this.Inventory.value.Device_ID).length != 15){
      let message1="Device Id must be of 15 digit";
      let action:any;
      this.snackBar.open(message1, action, {
        duration: 5000,
        
      });  
  
     }
    
    else{
      // submitData
      // this.Inventory.value.operator_id  = this.userid;
      this.Inventory.value.superAdmin = this.supAdminId;
      this.Inventory.value._id = this.objectID;
      if(this.dataDevModel != undefined){
        this.Inventory.value.device_model = this.dataDevModel[0]._id;
      }
   
      this.contactService.editDevInventory(this.Inventory.value).subscribe(res=>{
        console.log(res);
        console.log(res.message)
        let message1=res.message;
        let action:any;
        this.snackBar.open(message1, action, {
          duration: 5000,        
        });  
        this.router.navigateByUrl("Inventorylist");
      },err=>{
        console.log(err);
        let message1=JSON.parse(err._body).message;
        let action:any;
        this.snackBar.open(message1, action, {
          duration: 5000,         
        });  
  
      })
    }
  }


  selectedDevModel(devModel){
    this.DeviceModelValue = devModel;
    console.log(this.DeviceModelValue);
  
  }

  device_Model: any;
  getDeviceModel() {
    this.contactService.getDevModel()
      .subscribe(res => {
        this.device_Model = res;
        var devname = [];
        console.log("Device_Model",this.device_Model);
        for(var i = 0 ; i<this.device_Model.length;i++){
          var a = {
            model :this.device_Model[i].device_type,
            id : this.device_Model[i]._id
          }
          devname.push(a);
        }
        console.log(devname);
      })
  }

  filterDeviceModelState(devModelVal){ 
    if(devModelVal == ''){
      this.dataDevModel=[];
    }
    
    if (devModelVal) {
      const filterDevModelVal:any = devModelVal;
      this.dataDevModel=[];
        console.log('device_model' , this.device_Model);
       this.dataDevModel = this.device_Model.filter(function(k){
        
        var z = k.device_type.toLocaleLowerCase().indexOf(filterDevModelVal.toLocaleLowerCase());
      //  this.option = this.options[i];
  
        return z > -1;    
      });
      console.log("this.dataDevModel",this.dataDevModel);
        return this.dataDevModel;
  }
  
  }
}
