
import { environment } from './../../environments/environment';
import { Component, OnInit, OnDestroy} from '@angular/core';
import {DatainjectionService} from '../datainjection.service'
import * as io from 'socket.io-client';
import { Injectable } from '@angular/core';
import{Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AddGroupComponent } from '../add-group/add-group.component';
import { MdDialog } from '@angular/material';
import { SOSAlertComponent } from '../sosalert/sosalert.component';
import { CommentWindowComponent } from '../comment-window/comment-window.component';


@Component({
  selector: 'app-notification',
  templateUrl: './notification.component.html',
  styleUrls: ['./notification.component.scss']
})
@Injectable()
export class NotificationComponent implements OnInit, OnDestroy {

  dev_url:any;
  superAdmin: any;

  constructor(private injectData:DatainjectionService,private http: Http,private router: Router,public dialog: MdDialog) {
   
 
   this.dev_url  = environment.hostUrl; 
 
   }
   address:any;
  try:any;
  devicess:any;
  final:any = null;
  userID:any;
  fs:any;
  ls:any;
  or:any;
  emailid:any;
  useridd:any;
  custtype:any;
  cust:boolean = false;
  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)
  window.localStorage['mapLoad_ID'] = did
  this.router.navigateByUrl("location");
  }
  accListener(){
    var outerThis = this;
    return function(msg){
      // console.log(msg);
      
      // debugger; theft alert
      if((outerThis.superAdmin=== true)&&(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("msg12",msg);
        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();
       
        let data = {
          date:final_date,
          time:tm,
          data:msg.item.sentence,
          did:msg.device,
          user:msg.user,
          _id : msg._id
        }
        ++ outerThis.final_counter;
        // console.log("msgmsgmsgmsgmsgmsgmsgmsgmsgmsg",msg);
        if(msg.priority== 3){
          // console.log("open msg box");
          outerThis.playAudio(3);
          outerThis.openAlertBox(msg);
         
        }else{
          // console.log("open msg box else block")
          outerThis.playAudio(1);
        }
  
        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/getRecent?user='+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

  ngOnInit() {
   
    
   /*  this.final_counter=window.localStorage.Notifi_Counter */
    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.GET_notif = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).GET_notif; 
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    if(this.custtype == true){
      this.cust = true;
    }  
    if(this.mb.charAt(0)=="n"){
      this.mb = ' '
    }

    this.socket_Notify = this.injectData.getSocket_notifIO();          
    this.socket_Notify.on('connect', function(this){ });
    this.socket_Notify.on( this.useridd, this.accListener());
    this.getData(this.useridd).subscribe(
      data => {
        console.log('Notification data on every click',data);
        this.final_data=[];
        this.devicess = data ;
        for(let r=0;r<this.devicess.length;r++){
          var dt = new Date(this.devicess[r].timestamp);
           let  day = dt.getDate(); 
           let  month = dt.getMonth()+1; 
           let  year = dt.getFullYear();
          if((this.devicess[r].address=="")||(this.devicess[r].address==null)){
            this.address = ""
          }else{
            this.address =  "at" + "  " + this.devicess[r].address
          }
         
           let final_date = day+"/"+month+"/"+year
          let tm = new Date(this.devicess[r].timestamp).toLocaleTimeString();
          if(this.devicess[r].commentSaved){
            
          }else{
            let data = {
              date:final_date,
              time:tm,
              data:this.devicess[r].item.sentence,
              did:this.devicess[r].device,
              address:this.address,
              user:this.devicess[r].user,
              _id:this.devicess[r]._id
            }

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

  }

  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.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){
          that.ngOnInit() ; 
        }
        });
  }
}
