import { environment } from './../../environments/environment';

import { Component, Output, OnInit,EventEmitter, ContentChildren, QueryList, AfterContentInit,ViewChild } from '@angular/core';
import { DashComponent } from '../dash/dash.component';
import {ContactService} from '../contact.service';
import {Graph} from '../graph';
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { BrowserModule } from '@angular/platform-browser';
import { ChartsModule } from 'ng2-charts/ng2-charts';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';
import {Router, ActivatedRoute, Params} from '@angular/router';
import * as io from 'socket.io-client';
import {DatainjectionService} from '../datainjection.service'
@Component({
 selector: 'form-wizard',
 templateUrl: './gateway.component.html',
 styleUrls: ['./gateway.component.css'],
 providers: [ContactService],
})
export class GatewayComponent implements OnInit {
 @ViewChild(BaseChartDirective) public chart: BaseChartDirective;
 // lineChart
 cor:any;
 username:any;
 otp:any;
 graphs: Graph[];
 graph: Graph;
 private socket;
 socket_5000 = environment.socket5000

// mos_channel_link = environment.mosChannel;
 logout(){
 
 window.localStorage.clear();
 this.router.navigateByUrl("login");
 // window.localStorage.removeItem('_i');
 //this.fs.clearCache();
 //this.router.navigateByUrl("login");
 // this.activatedRoute.queryParams.subscribe((params: Params) => {
 // let userId = params['_i'];
 // userId === null;
// });
// this.fs === null;
 // this.ls === null; 
 // this.or === null;
 
 
 }
 addContact2(){
console.log(this.graphs);
 /* setInterval(function(){alert("Hello")},3000) */
console.log(this.otp);

}
ideal(){
 this.router.navigateByUrl("device-report/ideal-report");
}

_lineChartData:any;
public info: string;
public prevDatasets;
public datasets = [
 {
 label: "Humidity",
 data: [1, 1, 1, 1, 1, 1]
 }
];
public datasetss = [
 {
 label: "Rack 2",
 data: [0, 0, 0, 0, 0, 0]
 }
];
public datasetsss = [
 {
 label: "Rack 1",
 data: [0, 0, 0, 0, 0, 0]
 }
];
public datasetssss = [
 {
 label: "Sleep Mode Temprature",
 data: [0, 0, 0, 0, 0, 0]
 }
];
public labels = ['', '', '', '', '', ''];
public labelss = ['', '', '', '', '', ''];
public labelsss = ['', '', '', '', '', ''];
public labelssss = ['', '', '', '', '', ''];

public options = {
 scales: {
 yAxes: [{
 ticks: {
 beginAtZero: false,
 max: 100,
 min: 0
 }
 }] 
 }
};
public optionss = {
 scales: {
 yAxes: [{
 ticks: {
 beginAtZero: true,
 max: 100,
 min: 0
 }
 }] 
 }
};
public optionsss = {
 scales: {
 yAxes: [{
 ticks: {
 beginAtZero: true,
 max: 100,
 min: 0
 }
 }] 
 }
};
public optionssss = {
 scales: {
 yAxes: [{
 ticks: {
 beginAtZero: true,
 max: 250,
 min: 0
 }
 }] 
 }
};

change() {
 this.datasets = [{
 label: "Humidity",
 data: []
 }];
 
 this.labels = [];
}
changee() {
 this.datasets = [{
 label: "Distance",
 data: []
 }];
 
 this.labels = [];
}
changeee() {
 this.datasets = [{
 label: "Distance",
 data: []
 }];
 
 this.labels = [];
}
changeeee() {
 this.datasets = [{
 label: "Distance",
 data: []
 }];
 
 this.labels = [];
}
sendsocket(){
 console.log("Running ON Socket");
 var devicename = "qlikAway_Smartswitch";
 var command = "on";
 this.socket.emit('publish',{topic:devicename,payload:command}); 
 
}
sendsocketoff(){
 console.log("Running OFF Socket");
 var devicename = "qlikAway_Smartswitch";
 var command = "off";
 this.socket.emit('publish',{topic:devicename,payload:command}); 
 
}
time:any;
tem:any;
clickData_CorrectAnimation() {

 
 this.socket.on('mqtt', (msg) => {
 
 // console.log(msg);
 // console.log(msg.topic +" => "+ msg.payload);
 if(msg.topic==="humid")
 {
 //console.log(new Date().toISOString());
 this.time = new Date().toLocaleTimeString();
 //this.a= this.time.split("T")[1];
 
 this.humid = parseFloat(msg.payload); 
 let newData = this.datasets[0].data.slice();
 let newTime = this.labels.slice();
 newData.shift();
 newTime.shift();
 newData.push(this.humid);
 // newTime.push(this.a);
 this.datasets = [{
 label: "Humidity",
 data: newData
 }];
 this.labels.shift();
 this.labels.push(this.time)
 // this.labels = newTime;
 console.log(this.labels);
 }
 else if(msg.topic ==="distance21"){
 console.log("************Sleep Mode TIME DATE**************")
 console.log(msg.payload) 
 console.log(new Date()) 
 console.log("**********************************************")
 this.dist = parseFloat(msg.payload); 
 let newDataaaa = this.datasetssss[0].data.slice();
 let newTimee = this.labels.slice();
 
 
 if(this.dist){
 // console.log("Dist TRue")
 this.timee = new Date().toLocaleTimeString();
 // console.log(this.dist);
 // console.log(this.timee);
 newDataaaa.shift();
 newDataaaa.push(this.dist);
 /* this.labelss.shift();
 this.labelss.push(this.timee) */
 this.dist = 0;
 this.timee = 0;
 }
 this.datasetssss = [{
 label: "Sleep Mode Temprature",
 data: newDataaaa
 }];
 // this.clickData_CorrectAnimationn()
 // this.clickData_CorrectAnimationnn()
 // this.clickData_CorrectAnimationnnn()
 //clickData_CorrectAnimationn
 } 
 /* else if(msg.topic==="distance2"){
 this.clickData_CorrectAnimationnn()
 
 } 
 else if(msg.topic==="distance3"){
 this.clickData_CorrectAnimationnnn()
 
 } */
 /* temp */
 else if(msg.topic==="temp"){
 this.temp = parseFloat(msg.payload); 
 console.log("************TIME DATE**************")
 console.log(msg.payload) 
 console.log(new Date()) 
 console.log("***********************************")

 /* T(°F) = T(°C) × 1.8 + 32

 */
 this.temp2 = this.temp * 1.8 + 32
 }
 else if(msg.topic==="gps"){
 this.lng = parseFloat(msg.payload.longitude);
 this.lat = parseFloat(msg.payload.latitude);
 }
 });
 
 
 
 
 /* this.contactService.getDataObservable(this.mos_channel_link).subscribe(
 
 data => {
 this.testResponse = data
 
 console.log("Data at Component", this.testResponse);
 
 
 

 this.humid = parseFloat(this.testResponse.humidity[0]);
 let newData = this.datasets[0].data.slice();
 newData.shift();
 newData.push(this.testResponse.humidity[0]);
 
 this.datasets = [{
 label: "Humidity",
 data: newData
 }];

 
 
 }
 
 ); */

 } 

timee:any
t:any = 0;
 clickData_CorrectAnimationn() {

 this.socket.on('mqtt', (msg) => {
 
 
 if(msg.topic==="distance1")
 {
 console.log("Distance 1")
 
 console.log(msg.payload)
 
 this.dist = parseFloat(msg.payload); 
 let newDataa = this.datasetsss[0].data.slice();
 let newTimee = this.labels.slice();
 
 
 if(this.dist){
 // console.log("Dist TRue")
 this.timee = new Date().toLocaleTimeString();
 // console.log(this.dist);
 // console.log(this.timee);
 newDataa.shift();
 newDataa.push(this.dist);
 this.barChartData.push(this.datasetsss);
 /* this.labelss.shift();
 this.labelss.push(this.timee) */
 this.dist = 0;
 this.timee = 0;
 
 }
 this.datasetsss = [{
 label: "Rack 1",
 data: newDataa
 }];
 
 // this.labels = newTime;
 // console.log(this.labelss);
 
 } 
 });
 
 
 
 /* this.contactService.getDataObservable(this.mos_channel_link).subscribe(
 
 data => {
 this.testResponse = data
 
 console.log("Data at Component", this.testResponse);
 
 
 
 
 
 let newDataa = this.datasetss[0].data.slice();
 newDataa.shift();
 newDataa.push(this.testResponse.distance[0]);
 
 this.datasetss = [{
 label: "Distance",
 data: newDataa
 }];
 
 
 
 }
 
 ); */
 
 } 
 

 clickData_CorrectAnimationnn() {

 this.socket.on('mqtt', (msg) => {
 
 
 if(msg.topic==="distance2")
 {
 console.log("Distance2")
 
 
 this.dist = parseFloat(msg.payload); 
 let newDataaa = this.datasetss[0].data.slice();
 let newTimee = this.labels.slice();
 
 
 if(this.dist){
 // console.log("Dist TRue")
 this.timee = new Date().toLocaleTimeString();
 // console.log(this.dist);
 // console.log(this.timee);
 newDataaa.shift();
 newDataaa.push(this.dist);
 /* this.labelss.shift();
 this.labelss.push(this.timee) */
 this.dist = 0;
 this.timee = 0;
 }
 this.datasetss = [{
 label: "Rack 2",
 data: newDataaa
 }];
 
 // this.labels = newTime;
 // console.log(this.labelss);
 
 } 
 });
 
 
 
 /* this.contactService.getDataObservable(this.mos_channel_link).subscribe(
 
 data => {
 this.testResponse = data
 
 console.log("Data at Component", this.testResponse);
 
 
 
 
 
 let newDataa = this.datasetss[0].data.slice();
 newDataa.shift();
 newDataa.push(this.testResponse.distance[0]);
 
 this.datasetss = [{
 label: "Distance",
 data: newDataa
 }];
 
 
 
 }
 
 ); */
 
 } 





 clickData_CorrectAnimationnnn() {

 this.socket.on('mqtt', (msg) => {
 
 
 if(msg.topic==="distance21")
 {
 //console.log("Distance 3")
 
 
 
 this.dist = parseFloat(msg.payload); 
 let newDataaaa = this.datasetssss[0].data.slice();
 let newTimee = this.labels.slice();
 
 
 if(this.dist){
 // console.log("Dist TRue")
 this.timee = new Date().toLocaleTimeString();
 // console.log(this.dist);
 // console.log(this.timee);
 newDataaaa.shift();
 newDataaaa.push(this.dist);
 /* this.labelss.shift();
 this.labelss.push(this.timee) */
 this.dist = 0;
 this.timee = 0;
 }
 this.datasetssss = [{
 label: "Sleep Mode Temprature",
 data: newDataaaa
 }];
 
 // this.labels = newTime;
 // console.log(this.labelss);
 
 } 
 });
 
 
 
 /* this.contactService.getDataObservable(this.mos_channel_link).subscribe(
 
 data => {
 this.testResponse = data
 
 console.log("Data at Component", this.testResponse);
 
 
 
 
 
 let newDataa = this.datasetss[0].data.slice();
 newDataa.shift();
 newDataa.push(this.testResponse.distance[0]);
 
 this.datasetss = [{
 label: "Distance",
 data: newDataa
 }];
 
 
 
 }
 
 ); */
 
 } 










 public lineChartData:Array<any> =
 
 [
 
 {data: [], label: 'Humidity'}
]; 

public lineChartLabels:Array<any> = [];
public lineChartOptions:any = {
 responsive: true
};
public lineChartColors:Array<any> = [
 { // grey
 backgroundColor: 'rgba(148,159,177,0.2)',
 borderColor: 'rgba(148,159,177,1)',
 pointBackgroundColor: 'rgba(148,159,177,1)',
 pointBorderColor: '#fff',
 pointHoverBackgroundColor: '#fff',
 pointHoverBorderColor: 'rgba(148,159,177,0.8)'
 },
 { // dark grey
 backgroundColor: 'rgba(77,83,96,0.2)',
 borderColor: 'rgba(77,83,96,1)',
 pointBackgroundColor: 'rgba(77,83,96,1)',
 pointBorderColor: '#fff',
 pointHoverBackgroundColor: '#fff',
 pointHoverBorderColor: 'rgba(77,83,96,1)'
 },
 { // grey
 backgroundColor: 'rgba(148,159,177,0.2)',
 borderColor: 'rgba(148,159,177,1)',
 pointBackgroundColor: 'rgba(148,159,177,1)',
 pointBorderColor: '#fff',
 pointHoverBackgroundColor: '#fff',
 pointHoverBorderColor: 'rgba(148,159,177,0.8)'
 }
];

public lineChartLegend:boolean = true;
public lineChartType:string = 'line';

public randomize():void {
 let _lineChartData:Array<any> = new Array(this.lineChartData.length);
/* for (let i = 0; i < this.lineChartData.length; i++) {
 _lineChartData[i] = {data: new Array(this.lineChartData[i].data.length), label: this.lineChartData[i].label};
 for (let j = 0; j < this.lineChartData[i].data.length; j++) {
 _lineChartData[i].data[j] = Math.floor((Math.random() * 100) + 1);
 }
 } */
 for(let i=0;i< this.lineChartData.length; i++){
 _lineChartData[i] = this.otp;
 }
 this.lineChartData = _lineChartData;
}

// events
/* public chartClicked(e:any):void {
 console.log(e);
} */
constructor(private contactService:ContactService, private activatedRoute: ActivatedRoute,private router: Router, private injectData:DatainjectionService){

}
public barChartOptions:any = {
 scaleShowVerticalLines: false,
 responsive: true
};
public barChartLabels:string[] = ['', '', '', '', '', '', ''];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;

/* change() {
 this.datasets = [{
 label: "Humidity",
 data: []
 }];
 
 this.labels = [];
} */
public barChartData:any[] = [
 {data: [], label: 'Rack'}
];

// events
public chartClicked(e:any):void {
 console.log(e);
}

public chartHovered(e:any):void {
 console.log(e);
}






testResponse :any;
lat: any;
lng:any;
temp:any = 0;
temp2:any = 0;
humid:any;
dist:any;
Chart:any;
i=0;
a:any;
fs:any;
ls:any;
or:any;
ngOnInit() {
 this.fs = "Gaurav";
 this.ls = "Gupta";
 this.or = "adnate"
/* this.activatedRoute.queryParams.subscribe((params: Params) => {

 let userId = window.localStorage['token'] = params['_i'];

 this.fs = JSON.parse(window.atob(userId.split(".")[1])).fn;
 this.ls = JSON.parse(window.atob(userId.split(".")[1])).ln;
 this.or = JSON.parse(window.atob(userId.split(".")[1]))._orgName;

 function splitString(stringToSplit, separator) {
 var arrayOfStrings = stringToSplit.split(separator);
 
 
 this.fs = JSON.parse(window.atob(arrayOfStrings[1])).fn;
 
 
 }
 
 var comma = '.';
 
 
 }); */

/* Observable.interval(2000).subscribe(x => {
 
 
 
 
 this.contactService.getDataObservable(this.mos_channel_link).subscribe(
 
 data => {
 this.testResponse = data
 
 console.log("Data at Component", this.testResponse);
 this.clickData_CorrectAnimation();
 this.clickData_CorrectAnimationn();
 this.humid = parseFloat(this.testResponse.humidity[0]);
 this.dist = parseFloat(this.testResponse.distance[0]);
 this.temp = parseFloat(this.testResponse.temperature[0]);
 this.lat = parseFloat(this.testResponse.gps[0].longitude);
 this.lng = parseFloat(this.testResponse.gps[0].latitude);
 console.log("lat"+this.lat);
 console.log("lng"+this.lng);
 console.log("temp"+this.temp);
 console.log("humid"+this.humid);
 console.log("dis"+this.dist)
 
 
 }
 
 );
 }); */
 /* this.lineChartData[0].data.push(this.otp);
 
 this.contactService.getDataObservable(this.mos_channel_link).subscribe(
 
 data => {
 this.testResponse = data
 console.log("Data at Component", this.testResponse);

 this.lat = parseFloat(this.testResponse.gps[0]);
 this.temp = parseFloat(this.testResponse.temperature[0]);
 this.humid = parseFloat(this.testResponse.humidity[0]);
 console.log("lat"+this.lat);
 
 console.log("temp"+this.temp)
 console.log("humid"+this.humid)
 // this.lng = 78.9629; AIzaSyBipEX9tdWLlKYKtRqHB3laWqFH9J1SEk4
 this.lineChartData[0].data.push(this.humid);
 }
 
 ); */
 
 
 /* var mychartEle = document.getElementById('myChart');
 console.log(mychartEle);
 var ctx = mychartEle.getAttribute;
 console.log(ctx); */
/* var chart = new this.Chart(ctx, {
 type: 'line',
 data: {
 datasets: [{
 data: []
 },{
 data: []
 }]
 },
 options: {
 scales: {
 xAxes: [{
 type: 'realtime'
 }]
 }
 }
 }); */
 console.log("Sockets....");
 
 this.socket = this.injectData.getSocket_5000();
 io.connect(this.socket_5000);
 this.socket.on('connect', function(){
 console.log("IO Connected");
 
 });


 /* Commented bcz the mqtt socket is not working || Please Renove Comment " this.clickData_CorrectAnimation();" for temprature graph */

 
 this.clickData_CorrectAnimation();
 //this.clickData_CorrectAnimationn();
 
} 

}