import { Component, OnInit,Inject } from '@angular/core';
import { MdDialogRef,MD_DIALOG_DATA, MdSnackBar } from '@angular/material';
import { ContactService } from '../../contact.service';
import { BsDatepickerConfig } from 'ngx-bootstrap';
declare var $:any;

@Component({
  selector: 'app-add-reminder',
  templateUrl: './add-reminder.component.html',
  styleUrls: ['./add-reminder.component.scss']
})
export class AddReminderComponent implements OnInit {
  useridd: any;
  reminderDate = new Date();
  bsConfig: Partial<BsDatepickerConfig>;
  colorTheme = 'theme-dark-blue';
  priorReminder:number=0;
  device_id :any;
  statusChangeDate : any = new Date() ; 
  date_of_service:any=new Date();
  totalodo:any=0;
  odometer
  jobStatus :any ; 
  selectedDevice
  typeStatus = [{viewValue:"Pending", value:"Pending"},{viewValue:"In Progress", value:"In Progress"},{viewValue:"Completed", value:"Completed"}]
  reminderType :any=[
{ viewValue:"Service", value:"Service", },
{ viewValue:"Oil Change", value:"Oil Change", },
{ viewValue:"Tyres", value:"Tyres", },
{ viewValue:"Maintenance", value:"Maintenance", },
{ viewValue:"Auto Repair", value:"Auto Repair" },
{ viewValue:"Body Work", value:"Body Work" },
{ viewValue:"Diagnostics", value:"Diagnostics" },
{ viewValue:"Tune Up", value:"Tune Up" },
{ viewValue:"Brake Job", value:"Brake Job" },
{ viewValue:"Oil & Oil Filter Change", value:"Oil & Oil Filter Change" },
{ viewValue:"Tire Care", value:"Tire Care" },
{ viewValue:"Towing", value:"Towing" },
{ viewValue:"Wheel balance & Alignment", value:"Wheel balance & Alignment" },
{ viewValue:"Fleet", value:"Fleet" },
{ viewValue:"Auto Tracking", value:"Auto Tracking" },
{ viewValue:"A/C Repair", value:"A/C Repair" },
{ viewValue:"Others", value:"Others", }
]

  notifType = [
  {view:"SMS",value:"SMS"},{view:"EMAIL",value:"EMAIL"},{view:"PUSH NOTIFICATION",value:"PUSH_NOTIFICATION"}
  ];
  notificatinType:any;
  emailid: any;
  devicesss: any;


  finall: any;
  options :any=[];
  vehicleOption:boolean=false;
  reminder: any;
  additionalNote:any;
  deviceObject: any = [];
  UpdateTemplate: boolean = false ;
  performed_by: any;
  vehicleName
  constructor(public dialogRef: MdDialogRef<AddReminderComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,public snackBar: MdSnackBar) {

      $('#select_1').hide();
      this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme }); 
      this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;   
      this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;


      console.log('this.data',this.data);
      if(this.data.identifier === 'edit'){
        console.log('edit is working fine'); 
        this.UpdateTemplate = true ; 
        this.jobStatus = this.data.status ;   
        this.reminderDate = (this.data.reminder_date)?new Date(this.data.reminder_date):new Date();
        this.date_of_service = (this.data.date_of_service)?new Date(this.data.date_of_service):new Date();
        this.priorReminder = this.data.prior_reminder ;
        this.reminder = this.data.reminder_type ; 
        this.performed_by= this.data.performed_by;
        this.totalodo = this.data.odo ;
        this.vehicleName=this.data.Device_Name
        // this.notificatinType = this.data.notification_type ; 
        this.additionalNote = this.data.note ;
        this.device_id = this.data.device._id ;
        console.log("this.device_id",this.device_id); 
     
 

        // notificatinType
      

      }

     }

  ngOnInit() {

    this.getDevices();
  }

  getDevices(){
    
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(

      data => {
        this.devicesss = data
     
        this.finall = (this.devicesss.devices);

        for(let i=0;i<this.devicesss.devices.length;i++){

          // if(this.devicesss.devices[i].type_of_device =="Tracker"){

            let a ={
              value : this.devicesss.devices[i].Device_Name,
              viewValue:this.devicesss.devices[i].Device_Name,
              did:this.devicesss.devices[i].Device_ID,
              id:this.devicesss.devices[i]._id,
              user:this.devicesss.devices[i].user,
              // email: this.devicesss.devices[i].Email_ID,
              // deviceType: this.devicesss.devices[i].type_of_device
            }
            this.options.push(a);
          }

        // }
     
           console.log(this.options);
           let that = this;
           setTimeout(()=>{
            // if(that.data.identifier === 'edit'){
            //   that.device_id = that.data.device._id ;
            // }
          
            that.loadropdown();
          },100)  
      });
  
    }

    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_1').multipleSelect({
          width: 200,
          placeholder: 'Select device.....',
          filter: true,
          single: true,
          selectAll: false
      
        })
       // $('#select').show();
      }, 100);
  
  
    }


  testss:any;
  deviceArr:any;
  save(){
    var that= this;
  
    this.deviceArr =  $('#select_1').multipleSelect('getSelects','value');
    
    console.log('this.deviceArr',this.deviceArr); 
    that.deviceObject = that.options.filter(function(devobj) {
        if(devobj.id == that.deviceArr[0]){    
          return devobj;      
        } 
    })
    for(var i=0;i<this.options.length;i++){
      if(that.deviceArr[0]==this.options[i].id){
        this.vehicleName=this.options[i].value
      }
    }
   
    console.log('this.options',this.options);
    console.log('this.deviceObj=>',this.deviceObject);
    console.log('this.deviceArr=>',this.deviceArr);
     function showErr(msg){
      let message1;
      (msg=='nodevice')?message1="Please select device":(msg=='reminder')?message1="Please select reminder type":(msg=='notif')?message1="Please select notification type":''
      let action:any;
      return that.snackBar.open(message1, action, {
        duration: 5000,
      });   
    }

    (this.deviceArr.length==0)?showErr('nodevice'):(this.reminder==undefined)?showErr('reminder'):(this.notificatinType==undefined)?showErr('notif'):saveReminder();

    function saveReminder(){
      var notifObj={
        "SMS" : false,
        "EMAIL": false,
        "PUSH_NOTIFICATION":false
      };
      for(var i=0;i<that.notificatinType.length;i++){
        if(that.notificatinType[i]=="SMS"){
          notifObj.SMS = true ; 
        }else if(that.notificatinType[i]=="EMAIL"){
          notifObj.EMAIL = true ;
        }else{
          notifObj.PUSH_NOTIFICATION = true; 
        }
      }
   
   

      // that.reminderDate
      var reminderPayload = {
        created_by : that.useridd,
        user : that.deviceObject[0].user,
        device : that.deviceArr[0],
        reminder_type : that.reminder,
        notification_type : notifObj,
        reminder_date:  that.reminderDate.toISOString(),
        prior_reminder :that.priorReminder,
        status :'Pending',
        vehicleName:that.vehicleName
      }
      if(that.additionalNote != undefined){
        reminderPayload['note'] = that.additionalNote ; 
      }
      if(that.odometer){
        reminderPayload['odo'] = that.odometer ; 
      }
      console.log(reminderPayload);
      that.contactService.savereminder(reminderPayload).subscribe(res=>{
        if(res){
          let msg = "Reminder set for the vehicle";
          let action:any;
           that.snackBar.open(msg, action, {
            duration: 5000,
          });  
          that.dialogRef.close('reminder Saved');
        }

      },err=>{
        let msg = "Please Try Again";
        let action:any;
        return that.snackBar.open(msg, action, {
          duration: 5000,
        });
      })

    }

  }


  updateReminder(){
    this.deviceArr =  $('#select_1').multipleSelect('getSelects','value');
    console.log(this.deviceArr,this.options,this.selectedDevice);
    if(this.deviceArr){
      for(var i=0;i<this.options.length;i++){
       if(this.deviceArr[0]==this.options[i].id){
         this.vehicleName=this.options[i].value
       }
      
      }
    }else{
      for(var i=0;i<this.options.length;i++){
       if(this.device_id==this.options[i].id){
         this.vehicleName=this.options[i].value
       }
      //  this.device_id
      }
    }

  
    var data={
      rid: this.data._id,
      status : this.jobStatus,
      status_changed_on : this.statusChangeDate.toISOString(),
    };
    if(this.deviceArr){
      data['device']=this.deviceArr[0]
    }else{
      data['device']=this.device_id
    }
    if(this.vehicleName){
      data['vehicleName']=this.vehicleName
    }

    if(this.priorReminder != undefined){
    data['prior_reminder'] = this.priorReminder ;   
    }


    if(this.additionalNote != undefined){
      data['note'] = this.additionalNote ;   
      }

      if(this.reminder != undefined){
        data['reminder'] = this.reminder ;   
      }
      if(this.performed_by != undefined){
        data['performed_by'] = this.performed_by ;   
      }
      if(this.totalodo != undefined){
        data['odo'] = this.totalodo ;   
      }
      if(this.date_of_service != undefined){
        var dos = new Date(this.date_of_service);
        data['date_of_service'] = dos.toISOString() ;   
      }
    console.log(data);
    
    this.contactService.updateReminder(data).subscribe(res=>{
      console.log(res);
      if(res){
        let msg = "Reminder Updated";
        let action:any;
         this.snackBar.open(msg, action, {
          duration: 5000,
        });  
        this.dialogRef.close('Reminder updated');
      }
    },err=>{
      let msg = "Please Try Again";
      let action:any;
      return this.snackBar.open(msg, action, {
        duration: 5000,
      });
    })

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

}
