import { Component, OnInit,Output,EventEmitter } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {GmapComponent} from '../gmap/gmap.component';
import { EditScheComponent } from '../edit-sche/edit-sche.component';

import {RuleComponent} from '../rule/rule.component';
import { ExpansionPanelsModule } from 'ng2-expansion-panels';
import {ContactService} from '../contact.service';
import { TimeDurationPickerModule } from 'angular2-time-duration-picker';
import {Schedule} from '../shedule';
import {Scheduleb} from '../scheduleb';
import {Schedulec} from '../schedulec';
import { DatePipe } from '@angular/common';
import {Device} from '../device';
import * as moment from 'moment-timezone';
import * as io from 'socket.io-client';
import { FlashMessagesService } from 'angular2-flash-messages';
import {Router, ActivatedRoute, Params} from '@angular/router';
import { DatepickerModule as YourAlias } from 'angular2-material-datepicker'
@Component({
  selector: 'app-details',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.css'],
  providers: [ContactService,DatePipe]
})
export class AccountComponent implements OnInit {
  @Output() private onClose: EventEmitter<AccountComponent> = new EventEmitter();
  @Output() private onCancel: EventEmitter<any> = new EventEmitter();
  public cancel(): void {
    this.unselect();
    this.onCancel.emit();
}
private unselect(): void {
  //this.container.selectedPanel = undefined;
  this.onClose.emit(this);
}
  animal: string;
  name: string;
/*   foods = [
    {value: 'SMS', viewValue: 'SMS'},
    {value: 'Email', viewValue: 'Email'},
    {value: 'Push', viewValue: 'Push Notification'},
  ]; */
  foodss = [
    {value: 'Daily', viewValue: 'Daily'},
/*     {value: 'Weekly', viewValue: 'Weekly'},
    {value: 'Monthly', viewValue: 'Monthly'}, */
  ];
  
  devices = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];
  device: Device;
  Device_ID: string;
  schedules: Schedule[];
  schedule: Schedule;
  schedulesb: Scheduleb[];
  scheduleb: Scheduleb;
  schedulesc: Schedulec[];
  schedulec: Schedulec;
  action:any;
  rep:any;
  month : boolean =false;
  daydes : boolean =true;
  myForm:any;
  date:any;
  dayselM:any ;
  dayselT:any;
  dayselW:any;
  dayselTH:any;
  dayselF:any;
  dayselSa:any ;
  dayselSu:any ;
  Expiry:any;
  date1:any;
  date2:any;
 df:any
sheds:any;
on_uid:any;
off_uid:any;
on_time_h:any;
on_time_m:any;
timedecoff_h:any;
timedecoff_m:any;
on_time:any;
off_time:any;
on_time_h_e:any;
on_time_m_e:any;
str:any;
sub_minutes:any;
hours_conv:any;
hour_on:any;
minute_on:any;
off_time_h_e:any;
off_time_h:any;
off_time_m_e:any;
off_time_m:any;
sub_minute:any;
hours_con:any;
hour_off:any;
minute_off:any
mess:any;
mess2:any;
ontime:any
offtime:any;
dev:any;
did:any;
dexp:any;
onn_time: Date ;
offf_time: Date;
panel:any;
private socket;
matrixred(link){
  window.open(link);
}
saveForm(){
  
}

edit_schedule(a,b,c,d): void {
  let dialogRef = this.dialog.open(EditScheComponent, {
    width: '548px',
    data: { did: this.deviceid, Device_name: a,on_time: b,off_time:c,on_id:d}
  });
  dialogRef.afterClosed().subscribe(result => {

    this.on_table=[];
    this.tabledata();

  });
}
delete_schedule(did){

 this.contactService.delshu(did)
.subscribe(
  
  dev  => {
   this.dev = dev
   //this._flashMessagesService.show('Deleted Sucessfully !!', {  timeout: 1000});
   this.on_table=[];
   this.tabledata();
  }
  
);
  //this.on_table=[];
 // this.tabledata();
    
}


logout(){

  this.router.navigateByUrl("login");
}


soon(){

  this.router.navigateByUrl("const?_i="+window.localStorage.token);
  
}

openNav() {

   this.router.navigateByUrl("location?_dname="+ this.userId +"_id="+this.deviceid);
   
}

  addshe(onn_time,offf_time)
  
  {

    this.ontime = this.onn_time
    this.offtime = this.offf_time
    function randomString(length, chars) {
      var mask = '';
      if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
      if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if (chars.indexOf('#') > -1) mask += '0123456789';
      if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
      var result = '';
      for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
      return result;
        }
        this.on_uid=randomString(5, 'a#A');
        this.off_uid=randomString(6, 'a#A');



  this.did =this.userId;
  this.dexp=this.Expiry
    if(this.rep === "Daily" ){
      
 
 

     
        if(this.ontime === undefined){
        
          this._flashMessagesService.show('Error: Enter ON Time !!', {  timeout: 2000});
          
        }
        else if(this.offtime === undefined){
          this._flashMessagesService.show('Error: Enter OFF Time !!', {  timeout: 2000});
        }
        else if(this.ontime == this.offtime){
          this._flashMessagesService.show('Error: Same ON Time and OFF Time !!', {  timeout: 2000});
          
        }
        else{
      const newshe ={
        did : this.did,
        ontime: this.ontime,
        on_uid:this.on_uid,
        offtime: this.offtime,
        off_uid:this.off_uid ,
        wday: [this.dayselM,this.dayselT,this.dayselW,this.dayselTH,this.dayselF,this.dayselSa,this.dayselSu],
        dexp : this.dexp
        
     }

    
           this.contactService.addshe(newshe)
          .subscribe(schedule => {
            
              this._flashMessagesService.show('Congratulation you have sucessfully created the scheduler !!!', {  timeout: 1000});       
              this.tabledata();
              this.panel.cancel()
          this.schedules.push(schedule);
          this.null_fun();
          } , (err: any) => {
        
          if(err.status ==   500)
          {
            this.mess = err._body.split(":")[1] ;
            this.mess2 = this.mess.split("}")[0];
            this._flashMessagesService.show("Error: "+this.mess2, { timeout: 2000 });
          }     
        }
        );    
    }}
    else if(this.rep === "Weekly")
    {
     
       const newshe ={
       // repitation: this.rep,
       did : this.userId,
        on_time:this.on_time,
        on_uid:this.on_uid,
        off_time:this.off_time,
        off_uid:this.off_uid,
        w_day: [this.dayselM,this.dayselT,this.dayselW,this.dayselTH,this.dayselF,this.dayselSa,this.dayselSu],
        wexp : this.Expiry
     }  
   
      this.contactService.addshe(newshe)
      .subscribe(scheduleb => {
        this._flashMessagesService.show('Congratulation you have sucessfully created the scheduler !!!', {  timeout: 3000});       
        this.null_fun();
      this.contactService.getShe(this.devicename).subscribe(
        
        data => {
          this.sheds = data 
          this.final = this.sheds.daily_sched
       
        });

      this.schedulesb.push(scheduleb);
  
      }, (err: any) => { 
     
      if(err.status ==   500)
      {
        this.mess = err._body.split(":")[1] ;
        this.mess2 = this.mess.split("}")[0];
        
    
        this._flashMessagesService.show("Error: Scheduling For this Device Already Exict Please Remove Earlier one !!", { timeout: 7000 });
     
      } 

    }
    ); 
    }
    else if(this.rep === "Monthly")
    {
      let  fromdate =this.datepipe.transform(this.date1, 'yyyy-MM-dd');
      let  todate =this.datepipe.transform(this.date2, 'yyyy-MM-dd');
      
      const newshe ={
        did :  this.deviceid,
        fdate: fromdate,
        tdate: todate,
        ftime:this.on_time,
        on_uid:this.on_uid,
        ttime:this.off_time,
        off_uid:this.off_uid,
        mexp : this.Expiry

     } 
  

     var subbed = new Date(this.date1 - 3*60*60*1000); 
  
    /*  this.on_time = null; */
   /*  
    this.contactService.addshe(newshe)
    .subscribe(schedulec => {
      this._flashMessagesService.show('Congratulation you have sucessfully created the scheduler !!!', {  timeout: 3000});       
     this.null_fun();
    this.schedulesc.push(schedulec);
    console.log(schedulec.message);
    }, (err: any) => { console.log(err.status); 
      console.log(err);
    if(err.status ==   500)
    {
      this.mess = err._body.split(":")[1] ;
      this.mess2 = this.mess.split("}")[0];
      
      console.log(this.mess);
      this._flashMessagesService.show("Error: Scheduling For this Device Already Exict Please Remove Earlier one !!", { timeout: 7000 });
      console.log("Error"); 
    } 
  
  
  
  } 
  
  );  */
    
    }
    }
  
  onChange(value){
    if(value === "Daily"){
      this.daydes = true;
      this.dayselM = true ;
      this.dayselT = true ;
      this.dayselW = true ;
      this.dayselTH = true ;
      this.dayselF = true ;
      this.dayselSa = true ;
      this.dayselSu = true ;
      }
      else if(value === "Monthly")
      {
        this.daydes = false;
        this.dayselM = false ;
        this.dayselT = false ;
        this.dayselW = false ;
        this.dayselTH = false ;
        this.dayselF = false ;
        this.dayselSa = false ;
        this.dayselSu = false ;
        
      }
    else{
      this.daydes = true;
        this.dayselM = false ;
        this.dayselT = false ;
        this.dayselW = false ;
        this.dayselTH = false ;
        this.dayselF = false ;
        this.dayselSa = false ;
        this.dayselSu = false ;
      
    }
  }
  devi(){
    this.router.navigateByUrl("dashboard");

  }
  cond:Boolean = false;
  point : any = 0;
   a(){
   
     if(this.point == 0){
      this.cond = true;
      this.point ++;
     }
   else if(this.point % 2 == 0){
    this.cond = true;
    this.point ++;
   }
   else{
     this.cond = false
     this.point ++;
   }
  
    
  }
  report(){
    this.cond = false
    this.router.navigateByUrl("device-report");
  
  }
  report_speed(){
    // console.log("report speed call")
    this.cond = false
    this.router.navigateByUrl("device-report/device-speed-report");
  }
  
  delete(){
    // console.log("DELETE RUNNING");
  }
  jun = moment();
  constructor(private _flashMessagesService: FlashMessagesService,private router: Router,public datepipe: DatePipe,public dialog: MdDialog, private contactService: ContactService, private activatedRoute: ActivatedRoute) {

    
   }
  openDialog(): void {
    let dialogRef = this.dialog.open(GmapComponent, {
      width: '480px',
      data: { did: this.deviceid, animal: this.animal }
    });
    dialogRef.afterClosed().subscribe(result => {
      // console.log('The dialog was closed');

      this.contactService.getmatrix( this.deviceid).subscribe(
        
        mat_data => {
          this.mat = mat_data 
/*             this.final = this.sheds[length].daily_sched.ontime;
*/           
          // console.log(this.mat);
          // console.log( mat_data);
        }); 


      
      this.animal = result;
      // console.log(this.animal);
     /*  this.l.push(this.animal) */
    });
  }
  openDialog2(): void {
    let dialogRef = this.dialog.open(RuleComponent, {
      width: '700px',
      //data: { name: "1234567890", animal: this.animal }
    });
    dialogRef.afterClosed().subscribe(result => {
      // console.log('The dialog was closed');
     // this.animal = result;
     // console.log(this.animal);
     // this.l.push(this.animal)
    });
  }
  private l = [];
  userId:any;
  divinfo(){
 
  }
  fs :any;
  ls :any;
  or :any;
  userID :any;
  emailid :any;
  devicess:any;
  fm:any;
  deviceid:any;
  devicedata:any;
  devicename:any;
  final:any;
  final2:any;
  onGmt:any;
  offGmt:any;
  mat:any;
  on:any;
  off:any;
  f_on:any;
  f_off:any;
  d:any;
  f_did:any;
  f_onn:any;
  f_offf:any;
  f_didd:any;
  list:any;
  del:boolean=true;
  on_table = [];
 data:any;

 null_fun(){
  //  console.log("NULL CALLED");
  this.ontime = undefined;
  this.offtime = undefined;
  this.rep =  undefined;
  this.on_time=null;
  this.on_uid=null;
  this.off_time=null;
  this.off_uid=null;
  this.dayselM=null;
  this.dayselT=null;
  this.dayselW=null;
  this.dayselTH=null;
  this.dayselF=null;
  this.dayselSa=null;
  this.dayselSu=null;
  this.Expiry=null;


 }
 tabledata(){

  this.contactService.getShe(this.devicename).subscribe(
    
    data => {
    
      this.sheds = data 
      this.on_table = []
      this.on = this.sheds.split('|')[0];
      this.f_onn = this.on.split('-'[0]);
      this.f_on = this.f_onn[1]
      let final_ON = this.f_on.split(',')
   
  
      this.off = this.sheds.split('|')[1];
      this.f_offf = this.off.split('-'[0]);
      this.f_off  = this.f_offf[1];
      let final_OFF = this.f_off.split(',')
      

      this.d = this.sheds.split('|')[2];
      this.f_didd = this.d.split('-')[1];
      this.f_did =  this.f_didd



      let on_id = this.sheds.split('|')[3];
      let i_onid = on_id.split('-')[1];
      let f_onid =  i_onid.split('/')[0]
      for(let i=0;i<final_ON.length;i++)
      {
       
          
        let f_o_t = this.f_on.split(',')[i];
        let f_f_t = this.f_off.split(',')[i];
        let f_o_id = f_onid.split(',')[i];
        data={f_o_t,f_f_t,f_o_id}
        
        this.on_table.push(data); 
      }
      // console.log(this.on_table); 
    }, (err: any) => { console.log(err.status); 
      // console.log(err);
    if(err.status ==   500)
    {     
      // console.log("No Schedule")
     // this.on_table = null;
      //this.del = false;
      this.on_table = []
    }     
  })
 
 }

  ngOnInit() {
    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.activatedRoute.queryParams.subscribe((params: Params) => {
      let userId = params['_did'];
      var devicedata =  userId.split('.');
       this.deviceid = devicedata[0];
      this.devicename = devicedata[1];
      this.userId =  this.devicename;
    
        });


/*       this.contactService.getmatrix( this.deviceid).subscribe(
        
        mat_data => {
          this.mat = mat_data           
          console.log(this.mat);
          console.log( mat_data);
        });  */
       this.tabledata();
  }

}
