Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
GameList.js 9.61 KiB
import React, { Component, Fragment } from "react";
import {
  TouchableHighlight,
  Modal,
  Picker,
  Text,
  StyleSheet,
  View,
  TextInput,
  Button
} from "react-native";

import LocationTracker from "./LocationTracker";

class GameList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      factions: [],
      games: [],
      tracking: false,
      selectedGame: null,
      selectedFaction: null,
      factionPassword: null,
      passwordPopupVisible: false,
      editForm: false,
      userLocation: {
        latitude: null,
        longitude: null,
        latitudeDelta: null,
        longitudeDelta: null
      }
    };

    intervalID = 0; // Used for starting and stopping the tracking ticks
  }

  componentDidMount() {
    this.getGames();
  }

  setPopupVisible(visible) {
    this.setState({ passwordPopupVisible: visible });
  }

  // Get all the games from the server and set the state to the first game
  async getGames() {
    await fetch("https://tacs-testing.cf:8443/game/listgames")
      .then(response => response.json())
      .then(games => {
        this.setState({
          games,
          selectedGame: games[0]
        });
      })
      .catch(error => {
        console.log(error);
      });
    await this.getFactions();
  }
  // Get all the factions from the server
  getFactions() {
    fetch(`https://tacs-testing.cf:8443/game/${this.state.selectedGame.id}`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })
      .then(res => res.json())
      .then(gameInfo => {
        let newFactions = [{ factionName: "- -" }, ...gameInfo.factions];
        this.setState({
          factions: newFactions,
          selectedFaction: newFactions[0]
        });
      })
      .catch(error => {
        console.log(error);
      });
  }
  joinFactionPopup(faction) {
    if (faction) {
      this.setState({ passwordPopupVisible: true });
    }
  }

  joinFaction() {
    fetch("https://tacs-testing.cf:8443/faction/join-faction", {
      method: "PUT",
      headers: {
        Authorization: "Bearer " + this.props.token,
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        factionPassword: this.state.factionPassword,
        factionId: this.state.selectedFaction.factionId,
        game: this.state.selectedGame.id
      })
    })
      .then(response => response.json())
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
  }
  // Toggles the tracking boolean (some thought mistake somewhere makes this kinda weird ¯\_(ツ)_/¯ )
  handleTrackingChange() {
    this.setState({ tracking: !this.state.tracking });
    if (!this.state.tracking) {
      this.startTracking();
    } else if (this.state.tracking) {
      this.stopTracking();
    }
  }

  // Start the player tracking with the wanted interval (ms)
  startTracking() {
    console.log("Pelaajan token : " + this.props.token);
    this.getCurrentLocation();
    let interval = 10000;
    this.intervalID = setInterval(() => {
      console.log(
        "Nyt träkätää nim birusti peliä: " + this.state.selectedGame.name
      );

      console.log(
        "Pelaajan latitude: " +
          this.state.userLocation.latitude +
          "Pelaajan longitude: " +
          this.state.userLocation.longitude
      );
      fetch(
        `https:/tacs-testing.cf:8443/tracking/location/${
          this.state.selectedGame.id
        }`,
        {
          method: "POST",
          headers: {
            Authorization: "Bearer " + this.props.token,
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            data: {
              type: "Feature",
              geometry: {
                type: "MultiPoint",
                coordinates: [
                  this.state.userLocation.latitude,
                  this.state.userLocation.longitude
                ],
                properties: {
                  time: null
                }
              }
            }
          })
        }
      )
        .then(res => res.json())
        .then(
          result => {
            console.log(result);
          },
          error => {
            console.log(error);
          }
        );
      console.log("Tracking: " + this.state.tracking);
    }, interval);
  }

  // Stop tracking the player
  stopTracking() {
    clearInterval(this.intervalID);
    console.log("Nyt lopetetaa seuranta.");
  }

  // Start & stop tracking depending on the boolean 'tracking' in state
  componentDidUpdate() {
    // if (this.state.tracking) {
    //   this.startTracking();
    // } else if (!this.state.tracking) {
    //   this.stopTracking();
    // }
  }
  // When you select a game with the picker, clears the tracking interval and gets the factions of the game
  selectGame = async (selectedGame, itemIndex) => {
    await this.setState({ selectedGame, tracking: false });
    await this.getFactions();
    await clearInterval(this.intervalID);
  };
  // When you select a faction, it asks you for a password, which is then sent to the server
  selectFaction = async (selectedFaction, itemIndex) => {
    await this.setState({ selectedFaction, tracking: false });
    await this.joinFactionPopup(this.state.selectedFaction.factionId);
    await clearInterval(this.intervalID);
  };
  //Getting the user location and storing it in the state
  getCurrentLocation = () => {
    const options = {
      enableHighAccuracy: true,
      timeout: 30000,
      maximumAge: 0
    };
    navigator.geolocation.getCurrentPosition(
      position => {
        console.log("Position : " + position);
        this.setState({
          userLocation: {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            latitudeDelta: 0.0522,
            longitudeDelta: 0.0421
          }
        });
      },
      err => console.log(err),
      options
    );
  };

  // Stop tracking on Unmount
  componentWillUnmount() {
    clearInterval(this.intervalID);
  }
  render() {
    const passwordPopup = (
      <Modal
        animationType="fade"
        transparent={true}
        visible={this.state.passwordPopupVisible}
        onRequestClose={() => {
          Alert.alert("Modal has been closed.");
        }}
      >
        <View style={styles.popupContainer}>
          <View style={styles.popup}>
            <Text style={styles.popupTitle}>{`Enter the password`}</Text>
            <TextInput
              style={styles.popupInput}
              placeholder="password"
              secureTextEntry={true}
              value={this.state.factionPassword}
              onChangeText={factionPassword =>
                this.setState({ factionPassword })
              }
            />
            <View style={styles.popupBottom}>
              <View style={styles.popupButton}>
                <Button
                  onPress={() => {
                    this.joinFaction();
                    this.setPopupVisible(!this.state.passwordPopupVisible);
                  }}
                  title="Submit"
                />
              </View>
              <View style={styles.popupButton}>
                <Button
                  onPress={() => {
                    this.setPopupVisible(!this.state.passwordPopupVisible);
                  }}
                  title="Close"
                />
              </View>
            </View>
          </View>
        </View>
      </Modal>
    );

    if (this.state.games.length > 0) {
      const items = (
        <Fragment>
          <Text style={styles.pickerTitle}>Selected Game:</Text>
          <Picker
            style={styles.picker}
            selectedValue={this.state.selectedGame}
            onValueChange={this.selectGame}
          >
            {this.state.games.map((game, i) => (
              <Picker.Item label={game.name} value={game} key={i} />
            ))}
          </Picker>
          {this.state.selectedGame && this.state.factions.length > 0 && (
            <Fragment>
              <Text style={styles.pickerTitle}>Selected Faction:</Text>
              <Picker
                style={styles.picker}
                selectedValue={this.state.selectedFaction}
                onValueChange={this.selectFaction}
              >
                {this.state.factions.map((faction, i) => (
                  <Picker.Item
                    label={faction.factionName}
                    value={faction}
                    key={i}
                  />
                ))}
              </Picker>
            </Fragment>
          )}
          {this.state.passwordPopupVisible && passwordPopup}
          <LocationTracker
            tracking={this.state.tracking}
            handleTrackingChange={this.handleTrackingChange.bind(this)}
          />
        </Fragment>
      );
      return <Fragment>{items}</Fragment>;
    } else return <Text>No games found.</Text>;
  }
}

const styles = StyleSheet.create({
  picker: {
    paddingBottom: 30
  },
  pickerTitle: {
    paddingTop: 10,
    fontSize: 20
  },
  popupContainer: {
    flex: 1,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#00000080"
  },
  popup: {
    width: 300,
    height: "auto",
    backgroundColor: "#fff",
    padding: 20
  },
  popupTitle: {
    fontSize: 20,
    textAlign: "center"
  },
  popupBottom: {
    padding: 10,
    marginBottom: 30,
    flexDirection: "row"
  },
  popupButton: {
    padding: 10
  },
  popupInput: {
    margin: 20,
    padding: 5,
    backgroundColor: "#e0e0e0"
  }
});

export default GameList;