import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {ContactService} from '../contact.service';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
declare var google: any;
@Component({
  selector: 'app-geofencing-view',
  templateUrl: './geofencing-view.component.html',
  styleUrls: ['./geofencing-view.component.scss'],
  providers: [ContactService]
})

export class GeofencingViewComponent implements OnInit {
  fs :any;
  ls:any;
  emailid:any;
  or:any;
  onn_time:any;
  min:any;
  before:any;
  corect_min:any;
  hr:any
  custtype:any;
  cust:boolean=false;
  run(){
  
  }
  mydealer(){
    window.localStorage['token'] =  window.localStorage['Dealer_token'];
    localStorage.removeItem('devices');
    window.localStorage['DataUpdate'] = 'True';
    if(window.localStorage['DataLoaded'] = 'True'){
      window.localStorage['Custumer'] = 'OFF'
      this.router.navigateByUrl("add")
     // this.router.navigateByUrl("const?_status="+"OK");
    }
  }
  myaccount(){
   
    let dialogRef = this.dialog.open(MyaccountComponent, {
      width: '903px',
      data: {}
    });
  
    dialogRef.afterClosed().subscribe(result => {
  
      if(result == "succ"){
        // console.log("Updated")
      }
  
    });
  }

  devicess:any;
  final:any;
  getdev(){
    let foods = []
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
        
      data => {
        this.devicess = data 
  
        let swap;
        for(let g = 0;g<this.devicess.devices.length-1;g++ ){
          for(let c = 0;c<this.devicess.devices.length-g-1;c++ ){
            if(this.devicess.devices[c].Device_Name>this.devicess.devices[c+1].Device_Name){
                swap = this.devicess.devices[c];
                this.devicess.devices[c] = this.devicess.devices[c+1];
                this.devicess.devices[c+1] = swap;
            }
          }
        }
        
        this.final = this.devicess.devices
       for(let i=0;i<this.devicess.devices.length;i++){
           let a ={
            value : this.devicess.devices[i].Device_Name,
            viewValue:this.devicess.devices[i].Device_Name
           }
           foods.push(a);
         }
      });
  }


 
    constructor(private router: Router,private contactService:ContactService,public dialog: MdDialog) { }

  
  
    soon(){
      this.router.navigateByUrl("const?_i="+window.localStorage.token);
      
    }
  
    cond:Boolean = false;
    point : any = 0;
     a(){
      // console.log(this.point);
       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 ++;
     }
    
      
    }
    
    Back(){
      this.router.navigateByUrl("geofencing");
    }

    draw(zzz,yyy){
      var map;
      var infoWindow;
     // console.log(typeof zzz)
      var GeoFencCoords = zzz
      var GeoName = yyy
     //  console.log(zzz[0].lat)
      initMap(GeoFencCoords);
      function initMap(GeoFencCoords) {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 17,
          center: {lat: GeoFencCoords[0].lat, lng: GeoFencCoords[0].lng},
          mapTypeId: 'terrain'
        });

        
        var bermudaTriangle = new google.maps.Polygon({
          paths: GeoFencCoords,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 3,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        });
        bermudaTriangle.setMap(map);

        // Add a listener for the click event.
        bermudaTriangle.addListener('click', showArrays);

        infoWindow = new google.maps.InfoWindow;
      }

      /** @this {google.maps.Polygon} */
      function showArrays(event) {
        // Since this polygon has only one path, we can call getPath() to return the
        // MVCArray of LatLngs.
        var vertices = this.getPath();

        var contentString = '<b>Geo Fence</b><br>' +
            'Name: ' + GeoName;

        // Iterate over the vertices.
     /*    for (var i =0; i < vertices.getLength(); i++) {
          var xy = vertices.getAt(i);
          contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
              xy.lng();
        }
 */
        // Replace the info window's content and position.
        infoWindow.setContent(contentString);
        infoWindow.setPosition(event.latLng);

        infoWindow.open(map);
      }
    }


    useridd:any;
 
    cordin = [];
    ideal(){
      this.router.navigateByUrl("device-report/ideal-report");
    }
    mb:any;
    logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
superAdmin:Boolean = false;
    ngOnInit() {
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
     this.logo=window.localStorage['logo'];
     this.text=window.localStorage['text'];
      let datacoming =window.location.search;
      console.log('datacomingdatacomingdatacomingdatacomingdatacoming=>',datacoming);
      let tblid = JSON.stringify(datacoming).split("=")[1].split('"')[0];
    
      this.contactService.getperGeoFence(tblid).subscribe(      
        data => {
          this.devicess = data 
          // console.log(this.devicess);
          let a = this.devicess[0].geofence.coordinates[0];
          for(let k=0;k<a.length;k++){
          let b ={
          lat : a[k][1],
          lng : a[k][0]
          }
          this.cordin.push(b);
          }  
          this.draw(this.cordin, this.devicess[0].geoname);
        });
 
      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.getdev();
      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
     }

    } 
  }
  
  
