import { Component, ViewChild , ElementRef} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { CommonProvider } from '../../providers/common/common';
import { Storage } from '@ionic/storage';
import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator/ngx';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

import {TranslateService} from '@ngx-translate/core';
import { SubjectService } from '../../providers/subject.service';
import { WebService_lang } from '../../providers/web.service';
import * as $ from 'jquery';
declare var google;


@IonicPage()
@Component({
  selector: 'page-detailed',
  templateUrl: 'detailed.html',
})

export class DetailedPage {

	@ViewChild('language') language: ElementRef;
	lang =  'en';

	//@ViewChild('map') mapElement: ElementRef;
	@ViewChild('maps') mapElement: ElementRef;
	shop_id:any;
	result:any;
	data:any;
	map: any;
	distnc:any;
	launchnavigator:any;


  constructor(
	public translate: TranslateService,
    public subjectService: SubjectService,
    public service_lang: WebService_lang, 
	public navCtrl: NavController,
	public navParams: NavParams,
	public service: CommonProvider,
	public storage: Storage,
	public iab: InAppBrowser) {
  	this.shop_id = navParams.get('shop_id');
  	console.log(this.shop_id);

  	this.data = {"source_lat":"9.9312","source_lng":"76.2673","destination_lat":"10.0178","destination_lng":"76.3333"}

  	this.storage.get('set_location').then(curr_data=>{
  		if(curr_data){
  			this.data.source_lat = curr_data.lat_lng.lat;
          	this.data.source_lng = curr_data.lat_lng.lng;
  		}          
	})
	
	this.subjectService.getLangData().subscribe(langData => {
		console.log(langData);
		this.lang = this.service_lang.getLocalStorageItem('lang');
		console.log(this.lang);
		if (this.lang) {
		  translate.setDefaultLang(this.lang);
		  translate.use(this.lang);
		}
	  });
  
	  
	  const lang  = this.service_lang.getLocalStorageItem('lang');
	  console.log(lang);
  
	  if(lang !== undefined){
		this.lang = lang;
	  }
  
	  if(this.lang === 'ru') {
		$('body').addClass('ru');
	  } else {
		$('body').removeClass('ru');
	  }
  
	  //this.lang = 'en';
  
	  translate.setDefaultLang(this.lang);
  
	  // the lang to use, if the lang isn't available, it will use the current loader to get them
  
	  translate.use(this.lang);

  	
  }
 source: any = [22.303894, 70.802160] // source lat,long
destination: any =  [23.022505, 72.571362] // dest lat,long

navigate(){
alert("called");
let options: LaunchNavigatorOptions = {
   start: this.source
};

 this.launchnavigator.navigate(this.destination, options)
   .then(
    success => alert('Launched navigator'),
    error => alert('Error launching navigator: ' + error)
 );
}

  ionViewDidLoad() {
    console.log('ionViewDidLoad DetailedPage');
    var post_data = {"id":this.shop_id,"token":""}
    var This = this;
  	this.storage.get('token').then(data => {
  		if(data){
  			post_data['token'] = data;
  		}  	
	})

	this.service.show_loader();

	this.service.post_data('shop_details',post_data).subscribe(data=>{
  		this.result = data; 
  		console.log(this.result);
  		this.service.hide_loader();

  		this.data.destination_lat = this.result.shop.latitude;
        this.data.destination_lng = this.result.shop.longitude;
    	

  		setTimeout(() => {
  			console.log(this.data)
        	This.loadMap();
      	}, 500);
  		
  		//console.log(data);
  	})

  	

  }
  navv(){
  	const source = this.data.source_lat+","+this.data.source_lng;
  	const dest = this.data.destination_lat+","+this.data.destination_lng;
  	this.iab.create("https://www.google.com/maps?saddr="+source+"&daddr="+dest, "_system");
  	
  }

 	loadMap(){
		console.log('load');
		var directionsDisplay = new google.maps.DirectionsRenderer;
		var directionsService = new google.maps.DirectionsService;
		let latLng = new google.maps.LatLng(this.data.source_lat,this.data.source_lng);

		let mapOptions = {
			center: latLng,
			zoom: 15,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		var icon = {
			url: "assets/icon/user.png", // url
			scaledSize: new google.maps.Size(30, 30), // scaled size
			origin: new google.maps.Point(0,0), // origin
			anchor: new google.maps.Point(25, 25) // anchor
		};
		
		

		this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
		directionsDisplay.setMap(this.map);
		 directionsDisplay.setOptions( { suppressMarkers: true } );
		this.calculateAndDisplayRoute(directionsService, directionsDisplay);

		var markers= new google.maps.Marker({
			animation: google.maps.Animation.DROP,
			position: new google.maps.LatLng(this.data.source_lat,this.data.source_lng),
			icon: icon,
			/*label: {
                text: name,
                color: 'black',
			}*/
		});
		
		markers.setMap(this.map);
		
		var icon1 = {
			url: "assets/icon/shop.png", // url
			scaledSize: new google.maps.Size(30, 30), // scaled size
			origin: new google.maps.Point(0,0), // origin
			anchor: new google.maps.Point(25, 25) // anchor
		};
		var markers1= new google.maps.Marker({
			animation: google.maps.Animation.DROP,
			position: new google.maps.LatLng(this.data.destination_lat,this.data.destination_lng),
			icon: icon1,
			/*label: {
                text: name,
                color: 'black',
			}*/
		});
		
		markers1.setMap(this.map);
		
		//this.addmarker_user(this.data,this.data,directionsService,directionsDisplay);
		
	}
	
	calculateAndDisplayRoute(directionsService,directionsDisplay){
		
		var selectedMode ="DRIVING";
		
		
		 var This =this
		
		directionsService.route({
			//origin: {lat:Number(this.userdata.crnt_lattitude), lng:Number(this.userdata.crnt_longitude)},  // Haight.
			//origin: {lat:Number(this.userdata.crnt_lattitude), lng:Number(this.userdata.crnt_longitude)},  // Haight.
			origin: {lat:Number(this.data.source_lat), lng:Number(this.data.source_lng)},  
			destination: {lat:Number(this.data.destination_lat), lng:Number(this.data.destination_lng)},  
			travelMode: google.maps.TravelMode[selectedMode]
        }, function(response, status) {
			console.log(response)
			if (status == 'OK') {
				var point = response.routes[ 0 ].legs[ 0 ];
				console.log(point)
				This.distnc = point.duration.text 
				console.log(This.distnc);
				//$( '#travel_data' ).html( 'Estimated travel time: ' + point.duration.text + ' (' + point.distance.text + ')' );
				/*
				
			var infowindow = new google.maps.InfoWindow({
					content: "ETA "+This.distnc,
					 
			});
				
			infowindow.open(This.map, markers);
		 
			google.maps.event.addListener(markers, 'click', function() {
				infowindow.open(This.map, markers);
			});
				*/
				
				directionsDisplay.setDirections(response);
			} else {
				window.alert('Directions request failed due to ' + status);
			}
			
        });
	}

	back(){
		this.navCtrl.pop();
	}

	book(){
		console.log(this.result);
		this.navCtrl.push('ServicePage',{'shop':this.result});
	}



  

}
