From 02d33137e9164037e0c1b685a30a28a2e54b9fca Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Taneli=20Riihim=C3=A4ki?= <m3034@student.jamk.fi>
Date: Fri, 5 Jul 2019 11:55:42 +0300
Subject: [PATCH] Get the tracking demo to work(ish)

---
 App.js                 |  19 ----
 components/GameList.js | 210 ++++++++++++++++++++++++++++++++++-------
 components/Login.js    |   2 +-
 3 files changed, 179 insertions(+), 52 deletions(-)

diff --git a/App.js b/App.js
index 38fe61d..22f1e9a 100755
--- a/App.js
+++ b/App.js
@@ -4,25 +4,6 @@ import { StyleSheet, View } from "react-native";
 import Login from "./components/Login";
 
 export default class App extends Component {
-  state = {
-    userLocation: null
-  };
-  // Getting the user location and storing it in the state
-  userTrackingHandler = () => {
-    navigator.geolocation.getCurrentPosition(
-      position => {
-        this.setState({
-          userLocation: {
-            latitude: position.coords.latitude,
-            longitude: position.coords.longitude,
-            latitudeDelta: 0.0522,
-            longitudeDelta: 0.0421
-          }
-        });
-      },
-      err => console.log(err)
-    );
-  };
   render() {
     return (
       <View style={styles.container}>
diff --git a/components/GameList.js b/components/GameList.js
index 292adc3..5c13c42 100644
--- a/components/GameList.js
+++ b/components/GameList.js
@@ -1,5 +1,14 @@
 import React, { Component, Fragment } from "react";
-import { Picker, Text, StyleSheet } from "react-native";
+import {
+  TouchableHighlight,
+  Modal,
+  Picker,
+  Text,
+  StyleSheet,
+  View,
+  TextInput,
+  Button
+} from "react-native";
 
 import LocationTracker from "./LocationTracker";
 
@@ -12,6 +21,8 @@ class GameList extends Component {
       tracking: false,
       selectedGame: null,
       selectedFaction: null,
+      factionPassword: null,
+      passwordPopupVisible: false,
       editForm: false,
       userLocation: {
         latitude: null,
@@ -28,9 +39,13 @@ class GameList extends Component {
     this.getGames();
   }
 
+  setPopupVisible(visible) {
+    this.setState({ passwordPopupVisible: visible });
+  }
+
   // Get all the games from the server and set the state to the first game
-  getGames() {
-    fetch("https://tacs-testing.cf:8443/game/listgames")
+  async getGames() {
+    await fetch("https://tacs-testing.cf:8443/game/listgames")
       .then(response => response.json())
       .then(games => {
         this.setState({
@@ -41,6 +56,7 @@ class GameList extends Component {
       .catch(error => {
         console.log(error);
       });
+    await this.getFactions();
   }
   // Get all the factions from the server
   getFactions() {
@@ -51,19 +67,46 @@ class GameList extends Component {
         "Content-Type": "application/json"
       }
     })
-      .then(response => response.json())
-      .then(factions => {
-        console.log(factions);
+      .then(res => res.json())
+      .then(gameInfo => {
+        let newFactions = [{ factionName: "- -" }, ...gameInfo.factions];
         this.setState({
-          factions: factions.factions,
-          selectedFaction: factions[0]
+          factions: newFactions,
+          selectedFaction: newFactions[0]
         });
       })
       .catch(error => {
         console.log(error);
       });
   }
-  joinFaction() {}
+  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 });
@@ -76,6 +119,7 @@ class GameList extends Component {
 
   // 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(() => {
@@ -96,10 +140,25 @@ class GameList extends Component {
         {
           method: "POST",
           headers: {
+            Authorization: "Bearer " + this.props.token,
             Accept: "application/json",
             "Content-Type": "application/json"
           },
-          body: JSON.stringify({})
+          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())
@@ -130,16 +189,16 @@ class GameList extends Component {
     // }
   }
   // When you select a game with the picker, clears the tracking interval and gets the factions of the game
-  selectGame = (selectedGame, itemIndex) => {
-    this.getFactions();
-    clearInterval(this.intervalID);
-    this.setState({ selectedGame, tracking: false });
+  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 = (selectedFaction, itemIndex) => {
-    this.joinFaction();
-    clearInterval(this.intervalID);
-    this.setState({ selectedFaction, tracking: false });
+  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 = () => {
@@ -170,30 +229,83 @@ class GameList extends Component {
     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 => (
-              <Picker.Item label={game.name} value={game} />
+            {this.state.games.map((game, i) => (
+              <Picker.Item label={game.name} value={game} key={i} />
             ))}
           </Picker>
-          {this.state.selectedGame && (
-            <Picker
-              style={styles.picker}
-              selectedValue={this.state.selectedFaction}
-              onValueChange={this.selectFaction}
-            >
-              {this.state.factions.map(faction => (
-                <Picker.Item label={faction.name} value={faction} />
-              ))}
-            </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)}
@@ -207,7 +319,41 @@ class GameList extends Component {
 
 const styles = StyleSheet.create({
   picker: {
-    paddingVertical: 50
+    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"
   }
 });
 
diff --git a/components/Login.js b/components/Login.js
index 1f4a53a..33179f4 100644
--- a/components/Login.js
+++ b/components/Login.js
@@ -91,7 +91,7 @@ class Login extends Component {
                 onPress={this.handleLogout.bind(this)}
                 title="Logout"
               />
-              <GameList />
+              <GameList token={this.state.token} />
             </Fragment>
           )}
         </View>
-- 
GitLab