import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Alert,
  NetInfo,
  Geolocation
} from "react-native";
import Header from "../../components/Public/header";
import { observer, inject } from "mobx-react/native";
import { observable, transaction } from "mobx";
import { width, height } from "../../config/screen";
import MapView, { Polyline } from "react-native-maps";
import MapViewDirections from "react-native-maps-directions";
import AsyncStorageHelper from "../../config/asyncStorageHelper";

const asyncStorageHelper = new AsyncStorageHelper();

const origin = { latitude: 22.320508, longitude: 114.170222 };
const destination = { latitude: 22.320568, longitude: 114.171273 };
const GOOGLE_MAPS_APIKEY = "AIzaSyB_9Wi7BcAgqMPxZvW_5DWb8UxF5W9tWz0";

export const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      position => resolve(position),
      e => reject(e)
    );
  });
};

@inject(["menuStore"], ["userStore"])
@observer
export default class Location extends Component {
  title = "";
  pickUpPointLoaction = { latitude: 0, longitude: 0 };

  static navigationOptions = {
    drawerLabel: "My Orders"
  };

  constructor(props) {
    super(props);
    this.store = this.props.menuStore;
    this.userStore = this.props.userStore;
    this.state = {
      region: {
        latitude: null,
        longitude: null,
        latitudeDelta: 1,
        longitudeDelta: 1
      }
    };
  }

  getIndex(id) {
    var index = this.userStore.pickupPointLabel.findIndex(function(item, i) {
      return item.id == parseInt(id);
    });

    return index;
  }

  getUserLocation() {
    navigator.geolocation.getCurrentPosition(
      position => {
        this.userStore.userLocation = position;
      },
      error => {
        console.log(error);
      },
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );
  }

  componentWillMount() {
    const { navigation } = this.props;
    this.getUserLocation();
    this.title = navigation.getParam("title", "Location");
    this.pickUpPointLoaction = navigation.getParam("location", {
      latitude: 0,
      longitude: 0
    });
    this.setState({
      region: {
        latitude: this.userStore.userLocation.coords.latitude,
        longitude: this.userStore.userLocation.coords.longitude,
        latitudeDelta: 0.02,
        longitudeDelta: 0.02
      }
    });
  }

  clickMarkerAction(id) {
    Alert.alert(
      "",
      "Select " +
        this.userStore.pickupPointLabel[this.getIndex(id)].value +
        "?",
      [
        { text: "Cancel", onPress: () => console.log("Cancel") },
        { text: "Yes", onPress: () => this.picked(id) }
      ]
    );
  }

  picked(id) {
    asyncStorageHelper.saveData("pickupPointId", id);
    this.store.getMenuItem();
    this.props.navigation.goBack();
  }

  render() {
    console.log(this.userStore.userLocation);
    if (this.title == "Pick the loaction") {
      return (
        <View style={styles.container}>
          <Header title={this.title} navigation={this.props.navigation} />
          <MapView
            style={{ width: width, height: 400 }}
            showsUserLocation={true}
            initialRegion={this.state.region}
          >
            {this.userStore.pickupLoactionPoint.data.content.map(marker => (
              <MapView.Marker
                coordinate={{ latitude: marker.lat, longitude: marker.lng }}
                title={marker.name}
                onPress={() => this.clickMarkerAction(marker.id)}
              />
            ))}
          </MapView>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <Header title={this.title} navigation={this.props.navigation} />
          <MapView
            style={{ width: width, height: 400 }}
            showsUserLocation={true}
            initialRegion={this.state.region}
          >
            <MapView.Marker
              coordinate={{
                latitude: this.userStore.userLocation.coords.latitude,
                longitude: this.userStore.userLocation.coords.longitude
              }}
            />
            <MapView.Marker coordinate={this.pickUpPointLoaction} />
            <MapViewDirections
              origin={{latitude: this.userStore.userLocation.coords.latitude,
                longitude: this.userStore.userLocation.coords.longitude,}}
              destination={this.pickUpPointLoaction}
              apikey={GOOGLE_MAPS_APIKEY}
              mode = 'walking'
              strokeWidth={3}
              strokeColor="red"
            />
            )
          </MapView>
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});
