import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { interval } from 'rxjs/observable/interval';
import { Storage } from '@ionic/storage';
import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator';
import { SocialSharing } from '@ionic-native/social-sharing';

import { DevicesPage } from '../devices/devices'
import { ConfigurationPage } from '../configuration/configuration'
import { ShareService } from '../../services/share/share';
import { VespotServiceProvider } from '../../providers/vespot-service/vespot-service';

import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions
} from '@ionic-native/google-maps';

@Component({
  selector: 'page-home',
  templateUrl: 'main.html'
})
export class Main {

  private devicesPage;
  private configurationPage;
  devices: any;
  rootDevice: any;
  public rootPosition: any;
  map: GoogleMap;
  deviceMarker: any;
  newDevice: boolean = true;

  secondsCounter = interval(30000);

  constructor(private navCtrl: NavController,
  public shareService: ShareService,
  private googleMaps: GoogleMaps,
  private vespotService: VespotServiceProvider,
  public alertCtrl: AlertController,
  private storage: Storage,
  private launchNavigator: LaunchNavigator,
  private socialSharing: SocialSharing) {
      this.devicesPage = DevicesPage;
      this.configurationPage = ConfigurationPage;
      this.devices = this.shareService.getDevices();
      this.rootDevice = this.shareService.getRootDevice();
      this.rootPosition = {};

  }



  ionViewWillEnter() {
    if(typeof this.shareService.getRootDevice() == "undefined") {
      console.log('ionViewWillEnter: Entro al undefined');
      this.storage.get('rootDevice').then((valDevice)=>{
        if(valDevice == null) {
          console.log('ionViewWillEnter: Entro al valDevice == null ' + valDevice);
          this.navCtrl.push(DevicesPage);
        } else {
          console.log('ionViewWillEnter: Entro al else del valDevice es ' + valDevice);
          let auth = this.shareService.getAuthToken();
          this.vespotService.getDeviceById(auth, valDevice)
        	.subscribe(
              (data) => { // Success
                this.rootDevice = data[0];
                this.shareService.setRootDevice(this.rootDevice);
                this.getRootDevicePosition();
              },
              (error) =>{
      			       console.log('ionViewWillEnter: ' + error);
              }
            );
        }
      });

    } else {
      console.log('ionViewWillEnter: Entro al getRootDevice');
      this.getRootDevicePosition();
      //this.loadMap();
    }
  }

  getRootDevicePosition() {
    let auth = this.shareService.getAuthToken();
    this.vespotService.getPositionByDeviceId(auth, this.shareService.getRootDevice().id)
  	.subscribe(
        (data) => { // Success

          if(this.newDevice) {
            this.rootPosition = data[0];
            this.loadMap();
            this.secondsCounter.subscribe((n) => {
              this.updateMarker();
            });
            this.newDevice = false;
        } else {
            this.updateMarker();
        }
        },
        (error) =>{
			       console.log('getRootDevicePosition: ' + error);
        }
      );
  }

  /**
  GOOGLE MAPS
  **/
  loadMap(){

    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: this.rootPosition.latitude, // default location
          lng: this.rootPosition.longitude // default location
        },
        zoom: 18
      }
    };

    this.map = this.googleMaps.create('map_canvas', mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
    .then(() => {
      // Now you can use all methods safely.
      this.getPosition();
    })
    .catch(error =>{
      console.log('loadMap: ' + error);
    });

  }

  getPosition(): void{
    this.map.moveCamera({
      target: {
        lat: this.rootPosition.latitude, // default location
        lng: this.rootPosition.longitude // default location
      }
    });
    this.deviceMarker = this.map.addMarker({
      title: this.shareService.getRootDevice().name,
      icon: 'blue',
      position: {
        lat: this.rootPosition.latitude, // default location
        lng: this.rootPosition.longitude // default location
      }
    });
    this.deviceMarker.showInfoWindow();
    this.deviceMarker.setDisableAutoPan(true);
  }

  updateMarker() {
      let auth = this.shareService.getAuthToken();
      this.vespotService.getPositionByDeviceId(auth, this.shareService.getRootDevice().id)
    	.subscribe(
          (data) => { // Success
            if(data[0].serverTime != this.rootPosition.serverTime) {
              this.map.clear().then(() => {
                this.rootPosition = data[0];
                this.getPosition();
              }).catch(error =>{
                console.log('loadMap: ' + error);
              });
            }
          },
          (error) =>{
  			       console.log('updateMarker: ' + error);
          }
        );
  }

  shareViaMaps() {
    let options: LaunchNavigatorOptions = {
      start: 'Bogota, ON'
    };

    this.launchNavigator.navigate([this.rootPosition.latitude, this.rootPosition.longitude], options)
    .then(
      success => console.log('Launched navigator'),
      error => console.log('Error launching navigator', error)
    );
  }

  shareViaWhatsarpp() {
    //http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}
    this.socialSharing.share('Posición de mi dispositivo', '', null, 'http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141')
  }

}
