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

import { Router } from '@angular/router';
import { MyaccountComponent } from '../../../myaccount/myaccount.component';
import { MdDialog } from '@angular/material';
import { FlashMessagesService } from 'angular2-flash-messages';
import { ReportService } from '../../report.service';
import * as moment from 'moment';
import { DatainjectionService } from '../../../datainjection.service';
import { Http } from '@angular/http';
import { environment } from '../../../../environments/environment';
import { SOSAlertComponent } from '../../../sosalert/sosalert.component';
import { CommentWindowComponent } from '../../../comment-window/comment-window.component';
import { NotiLocationComponent } from './noti-location/noti-location.component';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"

@Component({
  selector: 'app-notification-master',
  templateUrl: './notification-master.component.html',
  styleUrls: ['./notification-master.component.scss']
})
export class NotificationMastersComponent implements OnInit {
  ignition_data: any;
  index1
  isCC:Boolean=true;
  dev_url:any;
  superAdmin1: any;
  devStatus
  myInput:any;
  selectedData
statusArray = [
    {name:"overspeed",status:false,value:"overspeed"},
    {name:"Geo-Fence",status:false,value:"Geo-Fence"},
    {name:"power",status:false,value:"power"},
    {name :"Fuel",status : false,value:"Fuel"},
    {name:"MAXSTOPPAGE",status:false,value:"MAXSTOPPAGE"},
    {name : "MAXIDLING",status : false,value:"MAXIDLING"},
    
  ];
  limitArr=[100,200,500,'All'];
  limit=20
  fs : any;
  ls : any;
  emailid : any;
  before:any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate=new Date();
  options=[];
  identifier:any='notification_master';
  logo:any;
  superAdmin:Boolean = false;
  // notifications=["overspeed",'Geo-Fence','Route','IGN','Fuel'];
  vehicles:any;
  fromdate=new Date();
  notifArray: any =[];
  dealerSelect: any[];
  dealerData: any;
  dealerObj: any;
  task=[]
  supAdmin: any;
private finalise = new Subject<void>();
  constructor(private injectData:DatainjectionService,private http: Http,private contactService: ContactService,private _service:ReportService,private router: Router,public dialog: MdDialog,private _flashMessagesService: FlashMessagesService) {
    
   this.dev_url  = environment.hostUrl; 
    this._service.invokeEventFornotificationMaster.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }      
      })
    // this.fromdate.setHours(0,0,0);


   }
   

    address:any;
  try:any;
  
  counter : any = 0;
  data:any;
  final_counter:any = 0;
  private socket_Notify
  final_data = [] 
  countfun(){
    if(this.final_counter == 0){
      return false
    }
    else{
      return true
    }
  }
  checker(){
    this.final_counter = 0;
    window.localStorage['Notifi_Counter'] = this.counter;

  }
  calldevice(did){
  console.log(did)
    this.dialog.open(NotiLocationComponent, {
    //  height:'300px',
    //   width:'500px',
      
      data: did
      });

  // window.localStorage['mapLoad_ID'] = did
  // this.router.navigateByUrl("location");
  }
  accListener(){
    var outerThis = this;
    return function(msg){
      // debugger; theft alert
     if((outerThis.superAdmin=== true || !outerThis.isCC)&&(msg.item._type === "Ignition Alert" || msg.item._type==="Theft Alert" || msg.item._type=="Max Stoppage Alert" || msg.item._type=="Max Idling Alert")){
        //  console.log("msgmsgmsgmsgmsgmsgmsgmsgmsgmsg",msg);
      }else{
        console.log("msg",msg.type,(outerThis.devStatus));
        var arr=[];
        arr=outerThis.devStatus?outerThis.devStatus:[]
        // for(var i=0;i<outerThis.devStatus.length;i++){
        if(arr.includes(msg.type) || outerThis.devStatus==undefined || outerThis.devStatus=="" || arr.length==0){
          var dt = new Date(msg.timestamp);
          let  day = dt.getDate(); 
           let  month = dt.getMonth()+1; 
           let  year = dt.getFullYear();
         
           let final_date = day+"/"+month+"/"+year
          let tm = new Date(msg.timestamp).toLocaleTimeString();
          var n = msg.item.sentence.split(" ");
          console.log(n[n.length - 1]);
          let data = {
            date:final_date,
            time:tm,
            data:msg.item.sentence,
            did:msg.device,
            user:msg.user,
            _id : msg._id,
            type:msg.type,
            last:n[n.length - 1],
            in:n.includes('exited')
          }
         console.log(data);
         
          ++ outerThis.final_counter;
         
          window.localStorage['Notifi_Counter'] = outerThis.final_counter;
          outerThis.final_counter=window.localStorage.Notifi_Counter
          outerThis.final_data.unshift(data);

        }
      // }
      }
     
    }

  }
getData(a){
  return this.http.get(this.dev_url  + '/notifs/getAssignedNoti?id='+a)
  .map(res => res.json());

 
}
audio:any;
GET_notif:boolean;

playAudio(notifSignal){
  // notification
  // console.log("SOS Alert");
  if(notifSignal == 3){
 
    this.audio = new Audio();
    this.audio.src = '../../assets/notifSOS.wav';
    this.audio.play();
    Audio.prototype.stop = function()
    {
        this.pause();
        this.currentTime = 0.0;
    }
    // auto-start
    // this.audio.play();
  }else{
    this.audio = new Audio();
    this.audio.src = '../../assets/notification.wav';
  
    // auto-start
    this.audio.play();
  }


}
// mb:any
dialogRef:any;
  openAlertBox(message){
    this.dialogRef = this.dialog.open(SOSAlertComponent, {
      height:'300px',
      width:'430px',
      
      data: {'socketData':message}
      });

      this.dialogRef.afterClosed().subscribe(result => {   
        if(result=="success"){}
        });
  }
  ngOnDestroy() {
    if( this.socket_Notify){
      this.socket_Notify.removeAllListeners()
    }
    this.finalise.next(void 0);
     /*  this.socket_Notify.removeAllListeners(this.useridd) */
  }

  openPopup(device){
    // console.log("popup opened");
    var that  =this;
document.getElementById("mdMenu").style.display="none"
    var commentWindow = this.dialog.open(CommentWindowComponent, {
    //  height:'300px',
    //   width:'500px',
      
      data: {'deviceData':device}
      });

      commentWindow.afterClosed().subscribe(result => {   
        console.log(result);
        
        if(result){
          for(var i=0;i<this.final_data.length;i++){
            if(this.final_data[i]._id==device._id){
              this.final_data.splice(i,1)
            }
          }
          // that.ngOnInit() ; 
          this.getTask()
        }
        });
  }
  ngOnInit() {
   
    // this.notifications;
    
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;

    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    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.supAdmin=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).supAdmin;
      if(this.custtype == true){
        this.cust = true;
      }  
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }

      if( window.localStorage['Custumer'] == 'ON'){
        this.logoutbut = false
        this.dealer = true
     }
     else{
         this.logoutbut = true
     }
       var cc= JSON.parse(window.atob(window.localStorage.token.split('.')[1])).customer_role;
 
    
     if(cc=="cc"){
       this.isCC=false;
     }  
     this.logo=window.localStorage['logo'];
     this.text=window.localStorage['text'];
     var fd = new Date().setHours(0,0,0);
     this.Fromdate = new Date(fd);
     this.firstcall=false;
     this.lastcall= false;
     this.socket_Notify = this.injectData.getSocket_notifIO();          
    this.socket_Notify.on('connect', function(this){ });
    this.socket_Notify.on( this.isCC?this.useridd:this.supAdmin, this.accListener());
    
    this.tableData = false;
    // this.getAllccData()
    this.getTask()
  }

  
notification:any;
tableData:boolean=true;
getNotification(){
  this.notifArray=[];
  var from= this.Fromdate
  var to = this.todate;
  console.log(this.Fromdate,this.todate);
 console.log('this.deviceArr',this.deviceArr);
 var user :any;
 this.Load=true;
 if((this.custtype != true)&&(this.superAdmin != true)){
    user = this.useridd
 }
 
 var limit = 20;
 var data={
   from_date:from,
    to_date:to,
    type:this.notification,
    vehicle:JSON.stringify(this.deviceArr),
    sortOrder: -1,
    skip: this.skip,
    limit:this.limit,
    user:user
 }
//  from,to,this.notification,this.deviceArr,user,this.skip,limit
  this.contactService.post('/notifs/getNotifByFilterss',data)
    .subscribe(res=>{
      this.tableData = true;
      this.notifArray =res;
      this.assignCopy()
      if(this.notifArray == 0){
        this.firstcall=true;
        this.lastcall=(this.skip>0)?false:true;
      }
      this.Load=false;
      console.log(this.notifArray);
    },err=>{
      this.Load=false;
      this.notifArray=[];
      this.firstcall=true;
      this.lastcall=(this.skip>0)?false:true; 
      if(err.status == 500){
        this.tableData = false;
        // this._flashMessagesService.show("No data available", { cssClass: 'alert-danger', timeout: 1500 });
      }
    })
}




deviceObj = [];

deviceSelect: any = [];
deviceName: any;



tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    // table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
      
    }

    tab_text=tab_text+"</table>";
   
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}
deviceArr:any=[];
getReport(event){
  this.deviceArr=[];
  console.log("inside function");
  if (event == 'getExcel') {
      this.exportExcel();
    } else if(event=='getPdf')
  {
    this.expotToPdf();
  }else{
    var deviceId: any;
    var tpdata = event ; 
    var that = this;
    var fd = new Date(tpdata.fromDate);
    var td  = new Date(tpdata.toDate);
    this.notification =tpdata.notitype;
    
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    this.Fromdate = fd;
    this.todate = td;
    console.log('event',event);
    this.skip = 1;
    this.firstcall=false;
    this.lastcall= true;
    this.getNotification();
 
  }
 
}

getTask(){
  console.log("In");
  
  this.getData(this.useridd).subscribe(
      data => {
        // console.log('Notification data on every click',data);
        this.task=[];
        var devicess = data ;
        var address
        for(let r=0;r<devicess.length;r++){
          var dt = new Date(devicess[r].timestamp);
           let  day = dt.getDate(); 
           let  month = dt.getMonth()+1; 
           let  year = dt.getFullYear();
          if((devicess[r].address=="")||(devicess[r].address==null)){
           address = ""
          }else{
           address =  "at" + "  " +devicess[r].address
          }
         
           let final_date = day+"/"+month+"/"+year
          let tm = new Date(devicess[r].timestamp).toLocaleTimeString();
          if(devicess[r].commentSaved){
            
          }else{
             var n = devicess[r].item.sentence.split(" ");
            //  date:final_date,
            // time:tm,
            // data:msg.item.sentence,
            // did:msg.device,
            // user:msg.user,
            // _id : msg._id,
            // type:msg.type,
            // last:n[n.length - 1],
            // in:n.includes('exited')
            let data = {
              date:final_date,
              time:tm,
              data:devicess[r].item.sentence,
              did:devicess[r].device,
              address:address,
              type:devicess[r].type,
              user:devicess[r].user,
              _id:devicess[r]._id,
              last:n[n.length - 1],
            in:n.includes('exited')
            }

            this.task.push(data);
          }
          // console.log('this.final_data',this.final_data);
        }
      }
    )
}


firstcall:boolean=true;
lastcall:boolean=true;
skip:number=1;
next() {
  // this.deviceData =[];
  this.lastcall=false;
  this.skip += 1; 
  // this.sidebarData();
  // this.ngOnInit();
  this.getNotification();   
}
pre() {
  // this.deviceData=[]
  // console.log(this.skip)
  if(this.skip>0){
    this.skip -= 1;   
    this.lastcall=false;
    // this.sidebarData();
    // this.ngOnInit();
    this.getNotification(); 
  }else{
    this.lastcall=true;
    this.firstcall=false;
  }
 
}


     expotToPdf(){
    console.log(this.notifArray);

    this.downloadPdf()
    
  }
// downloadPdf() {
//     let fileName =
//       "Notifications" +
//       new Date().getTime() +
//       PDF_EXTENSION;
//     var pdfsize = "a2";

//     var doc = new jsPDF("p", "pt", pdfsize);
//   //   var f_date = moment(this.from_date).format('lll'); 
//   // var t_date =moment(this.to_date).format('lll');
//   // var date_combine = f_date + ' to ' + t_date;
//   // doc.setFontSize(30);
//   doc.setFontSize(15);
//   doc.text('Notifications ', 20, 30);
//   // doc.text(date_combine, 250, 60);
//     doc.setFontStyle("arial");

//       var header = function(data) {
//     doc.setFontSize(15);
//     doc.setTextColor(40);
//     doc.setFontStyle('normal');
//     //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
//     // doc.text("Testing Report", data.settings.margin.left, 50);
//   };

//   var options = {
//     beforePageContent: header,
//     margin: {
//       top: 120
//     },
//     startY: doc.autoTableEndPosY() + 20
//   };

//     doc.autoTable({
//       head: this.headRows(),
//       // margin: { top: 80 },
//       body: this.bodyRows(this.notifArray.length, this.notifArray),
//       options
      
//     });
//     doc.save(fileName);
//   }
startAddress;

endAddress;
f_date
t_date
downloadPdf() {
  var outerThis=this
    let fileName =
      "Notification" +
      new Date()+
      PDF_EXTENSION;
    var pdfsize = "a2";
    var totalPagesExp = "{total_pages_count_string}";
//  outerThis.startAddress= outerThis.finalArr[0].address;
//  outerThis.endAddress= outerThis.finalArr[outerThis.finalArr.length-1].address
    var doc = new jsPDF("p", "pt", pdfsize);
    outerThis.f_date = moment(this.Fromdate).format('lll'); 
  outerThis.t_date =moment(this.todate).format('lll');
  // var date_combine = f_date + ' to ' + t_date;
  // doc.setFontSize(30);
   var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
  doc.setFontSize(15);
  // doc.text(60, 20, 'Travel Path Report (Date='+date_combine+') Device Name='+this.device_name,);
  
  doc.text("Notification", 500, 30);
    doc.setFontStyle("arial");

      var header = function(data) {
    doc.setFontSize(30);
    doc.setTextColor(40);
    doc.setFontStyle('arial');
  
  };

  var options = {
    beforePageContent: header,
    margin: {
      top: 120
    },
    
    startY: doc.autoTableEndPosY() + 20
  };
 var logo=localStorage.getItem('logo1');
 outerThis.toDataURL(logo, function (dataUrl) {
                
    doc.autoTable({
      head: outerThis.headRows(),
      // margin: { top: 80 },
      //  startY: doc.autoTable.previous.finalY + 200,
      body: outerThis.bodyRows(outerThis.notifArray.length, outerThis.notifArray),
      options,
       styles: {overflow: 'linebreak'},
      // tableLineColor: [0, 0, 0], //choose RGB
        // tableLineWidth: 0.5, //table border width
        // bodyStyles: {
        //     margin: 40,
        //     fontSize: 10,
        //     lineWidth: 0.2,
        //     lineColor: [0, 0, 0]
        // },
      theme:'grid',
      didDrawPage: function (data) {
        // Header
        doc.setFontSize(20);
        doc.setTextColor(40);
        doc.setFontStyle('arial');
        // logo=localStorage.getItem('logo1');
          if(logo)
              doc.addImage(dataUrl, 'JPEG', pageWidth-100, 6, 75, 75);
              doc.autoTable({html:"#headerTable",margin:{bottom:140,left:20,right:8,top:40},theme:'plain'});

        // Footer
        var str = "Page " + doc.internal.getNumberOfPages()
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
        }
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        var pageSize = doc.internal.pageSize;
        var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
        doc.text(str, data.settings.margin.left, pageHeight - 10);
    },
    
      margin: {top: 85},
     
    });
    if (typeof doc.putTotalPages === 'function') {
      doc.putTotalPages(totalPagesExp);
    }
    doc.save(fileName);
  })
  }

   toDataURL(url, callback) {
   
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }


  headRows() {

    return [
  // displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];

      {
        sentence:'Sentence',
        timestamp:'Date',
        comment:'Comment',
        // idle_time:'Duration',
        // ac_status:'AC Status',
        
      }
    ];
  }

  bodyRows(rowCount, pdfBody) {
    console.log(rowCount, pdfBody);

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({

       sentence:pdfBody[j].item.sentence,
        timestamp:moment(new Date(pdfBody[j].timestamp)).format('llll'),  
        comment:pdfBody[j].comment?pdfBody[j].comment:'N/A', 
        // idle_time:this.millisecondConversion(pdfBody[j].device.idle_time),
        // ac_status:pdfBody[j].device.ac_status?pdfBody[j].device.ac_status:'N/A'
      });
    }
    return body;
  }
  callDataTable(){

    this.skip = 0;
    // that.limit = len;
    this.getNotification();
  }

  selectedStatus(e){
    console.log(e,this.devStatus);
    
  }
  ccData
  getAllccData(){
    this.contactService.get('/users/getCCData?id='+this.useridd).subscribe((res:any)=>{
      console.log(res);
      this.ccData=res
      for(let i=0;i<this.ccData.length;i++){
          this.ccData[i].fullName=this.ccData[i].first_name+' '+this.ccData[i].last_name;
        }
    })
  }
  select(data,i){
    
    this.selectedData=data
    console.log(this.selectedData);
    this.index1=i
    console.log(this.selectedData);
    var data1={
      assigned_to:this.useridd,
      id:data._id,
      assigned_date:new Date()
    }
    this.contactService.post('/notifs/assignTo',data1).subscribe(res=>{
    console.log(res);
    for(var i=0;i<this.final_data.length;i++){
      if(data._id==this.final_data[i]._id){
        this.final_data.splice(i,1)
      }
    }
    this.getTask()
    this._flashMessagesService.show('Notification Assigned To you', { cssClass: 'alert-success', timeout: 3000 });
    })
  }
//    filtergrpStatess(val) {

//   console.log(val)
//   // console.log(this.options)
 
//   if (val) {
// // this.userDetail=undefined
//     const filtergrpValue:any = val;

//     this.dealerSelect=[];
//      this.dealerSelect = this.ccData.filter(function(g){
//       var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
//     // console.log("TESTINg",c)
//       return c > -1;    
//     });
//     if(this.dealerData){
//       for(let i=0;i<this.ccData.length;i++){
//         if(this.ccData[i].fullName==this.dealerData){
//           this.dealerObj=this.ccData[i]._id
//           console.log(this.ccData[i]);
//         }
//       }
//     }
//       console.log( this.dealerObj);
//       return this.dealerSelect;
//   }

// }

transfer(){
  
}
filteredItems:any
assignCopy(){
   this.filteredItems = Object.assign([], this.notifArray);
   console.log(this.filteredItems);
   
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.notifArray).filter(
      item => item.item.sentence.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
}


