
import { Component, Inject, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { BsDatepickerConfig, BsModalRef, BsModalService } from 'ngx-bootstrap';

import {
  MdDialog,
  MdDialogRef,
  MD_DIALOG_DATA,
  MdTabChangeEvent,
} from "@angular/material";
import { ContactService } from '../contact.service';
declare var swal: any;
@Component({
  selector: 'app-device-inventory-edit-popup',
  templateUrl: './device-inventory-edit-popup.component.html',
  styleUrls: ['./device-inventory-edit-popup.component.scss']
})

export class DeviceInventoryEditPopupComponent implements OnInit {
  failedDevices:any =[];

// imei:any;
// owner:any
// uploaded_By:any
// uploaded_Date:any
// billDate:any
// bllNumber:any
// state:any
// eSim_Validity:any
// deviceModal :any
// serial :any
// iccid_No:any
// mob1:any
// mob2:any
// status:any
// vendor:any
// purchase :any
// sold :any
// activation:any;
submitted= false;
deviceForm1:FormGroup;
  activationDate: any;
  useridd: any;
  constructor(public dialogRef: MdDialogRef<DeviceInventoryEditPopupComponent>,
    @Inject(MD_DIALOG_DATA) public data: any, private contactService: ContactService,private fb:FormBuilder) {
    
    this.failedDevices = data;
  }
  bsConfig: Partial<BsDatepickerConfig>;
  db_token: any;
  ngOnInit() {

    this.db_token = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    );
    this.useridd = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._id;
    console.log('userid',this.useridd)

    console.log("this.db_token=>", this.db_token);
    var fname=this.failedDevices.deviceObject.Owner?this.failedDevices.deviceObject.Owner.first_name?this.failedDevices.deviceObject.Owner.first_name:'':"";
      var lname=this.failedDevices.deviceObject.Owner?this.failedDevices.deviceObject.Owner.last_name?this.failedDevices.deviceObject.Owner.last_name:'':""
    this.activationDate = this.failedDevices.deviceObject.Activation_date
  ? new Date(this.failedDevices.deviceObject.Activation_date)
  : 'NA';
    this.deviceForm1 = this.fb.group({
      ownerName1: [fname + ' ' + lname,Validators.required],
      imei:[this.failedDevices.deviceObject.IMEI,[Validators.required,Validators.pattern('[0-9 ]{15}')]],
      uploaded_By:[this.failedDevices.deviceObject.uploaded_by.first_name + " " + this.failedDevices.deviceObject.uploaded_by.last_name,Validators.required],
      uploaded_Date:[this.failedDevices.deviceObject.Uploaded_date ? new Date(this.failedDevices.deviceObject.Uploaded_date): '',Validators.required],
      billDate:[this.failedDevices.deviceObject['BillDate'] ? new Date(this.failedDevices.deviceObject['BillDate']):'',Validators.required],
      billNumber:[this.failedDevices.deviceObject['BillNo'],Validators.required],
      state:[this.failedDevices.deviceObject['State'],Validators.required],//readable
      eSim_Validity:[this.failedDevices.deviceObject['eSIMValidaity']],
      deviceModal :[this.failedDevices.deviceObject['DeviceModelNo'],Validators.required],
      serial :[this.failedDevices.deviceObject['SerialNo'],Validators.required],
      iccid_No:[this.failedDevices.deviceObject['IccidNo'],Validators.required],
      mob1:[this.failedDevices.deviceObject['Mob1'],[Validators.required,Validators.pattern('[0-9 ]{13}')]],
      mob2:[this.failedDevices.deviceObject['Mob2'],[Validators.required,Validators.pattern('[0-9 ]{13}')]],
     status:[this.failedDevices.deviceObject.Status,Validators.required],
     vendor:[this.failedDevices.deviceObject.Vendor_Name],
     purchase :[this.failedDevices.deviceObject.Purchase_date ? new Date (this.failedDevices.deviceObject.Purchase_date): ''],
     sold :[this.failedDevices.deviceObject.Sold_date ? new Date(this.failedDevices.deviceObject.Sold_date) : ''],
     activation:[this.failedDevices.deviceObject.Activation_date ? new Date(this.failedDevices.deviceObject.Activation_date):''],
   });
   console.log("DEVICEFORM=>",this.deviceForm1);
  }

  closeModal(): void {
    this.dialogRef.close();
  }
  get f() { return this.deviceForm1.controls; }
  submit(){
    debugger
    this.submitted = true;
    if (this.deviceForm1.invalid) {
    console.log('working');
    return;
    }

   var data = {
      "IMEI": this.deviceForm1.value.imei,
      // "Vendor_Name":this.deviceForm1.value.vendor,
      "Uploaded_date":new Date(this.deviceForm1.value.uploaded_Date).toISOString(),
      "uploaded_by":this.db_token._id,
      "Status":this.deviceForm1.value.status,
      // "Purchase_date":new Date(this.deviceForm1.value.purchase).toISOString(),
      "BillDate" :new Date(this.deviceForm1.value.billDate).toISOString(),
      "BillNo" : this.deviceForm1.value.billNumber,
      "State" : this.deviceForm1.value.state,
      // "eSIMValidaity" :this.deviceForm1.value.eSim_Validity,
      "DeviceModelNo" :this.deviceForm1.value.deviceModal,
      "SerialNo" : this.deviceForm1.value.serial,
      "IccidNo" : this.deviceForm1.value.iccid_No,
      "Mob1" :this.deviceForm1.value.mob1,
      "Mob2" :this.deviceForm1.value.mob2,

    }
    if(this.deviceForm1.value.purchase){
      data['Purchase_date']=this.deviceForm1.value.purchase? new Date(this.deviceForm1.value.purchase).toISOString():'';
    }
    if(this.deviceForm1.value.vendor){
      data['Vendor_Name']=this.deviceForm1.value.vendor;
    }
    if(this.deviceForm1.value.eSim_Validity){
    data['eSIMValidaity']= this.deviceForm1.value.eSim_Validity;
    }

      this.contactService.editdevInv(data)
      .subscribe(
        response => {
          console.log('Device updated successfully:', response);
          swal("Updated", "Device Inventory Updated", "success");
        },
        error => {
         
          console.error('Error deleting device:', error);
        }
      );
    

    console.log('updated data values',data)
    this.closeModal();
  }
}
