Skip to content
111 changes: 37 additions & 74 deletions app/src/main/java/com/javaawesome/tag/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
Expand All @@ -18,12 +16,10 @@
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.amazonaws.amplify.generated.graphql.CreatePlayerMutation;
import com.amazonaws.amplify.generated.graphql.CreateSessionMutation;
import com.amazonaws.amplify.generated.graphql.ListPlayersQuery;
Expand Down Expand Up @@ -72,14 +68,19 @@ protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Transfer service registers a listener with Android OS for network connectivity changes
//If the network goes offline, the active transfers are paused
//Active transfers resume when the nextwork comes back online
//Works in the foreground and the background
getApplicationContext().startService(new Intent(getApplicationContext(), TransferService.class));

//If the app does not have course or fine location permission request them
if (this.checkSelfPermission(ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
this.checkSelfPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 10);
}

// initialize aws mobile client and check if you are logged in or not
//Initialize AWS mobile client and check if the player is logged in
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails result) {
Expand All @@ -95,19 +96,19 @@ public void onError(Exception e) {
}
});

// connect to AWS
//Connect to AWS
awsAppSyncClient = AWSAppSyncClient.builder()
.context(getApplicationContext())
.awsConfiguration(new AWSConfiguration(getApplicationContext()))
.build();

// initialize client for google location services
//Initialize client for google location services
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

//Initialize a new Linked List of game sessions
sessions = new LinkedList<>();

// initialize recycler view to display nearby game sessions
// TODO: have recycler view filter sessions by distance to user
//Initialize a recycler view to display game sessions within the defined distance of the player's location
recyclerNearbySessions = findViewById(R.id.recycler_nearby_sessions);
recyclerNearbySessions.setLayoutManager(new LinearLayoutManager(this));
this.sessionAdapter = new SessionAdapter(this.sessions, this);
Expand All @@ -117,20 +118,20 @@ public void onError(Exception e) {
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onresume called");
//If checkGpsStatus returns true to verify that the player's phone has GPS is turned on
if (checkGpsStatus()) {
// getCurrentUserLocation();
//Check if the player is already in the database
checkIfPlayerAlreadyExistInDatabase();
} else {
//Ask the player if they want to turn on their GPS to play
buildAlertMessageNoGps();
}
}

// Create new game session and go to map page
//Create a new game session and transfer the player to the games' map page
public void goToMap(View view) {
// TODO: check if player already exist in the database
EditText sessionName = findViewById(R.id.editText_session_name);
Log.i(TAG, "goToMap: "+sessionName.getText());
if(sessionName.getText().length()>0) {
CreateSessionInput input = CreateSessionInput.builder()
.title(sessionName.getText().toString())
Expand All @@ -151,37 +152,31 @@ public void onResponse(@Nonnull Response<CreateSessionMutation.Data> response) {

@Override
public void onFailure(@Nonnull ApolloException e) {
Log.e(TAG, "error in creating new game session" + e.getMessage());
Log.e(TAG, "Error in creating new game session" + e.getMessage());
}
});

//Send prompt to player that a session name is required before creating the new game
}else{
Toast.makeText(getBaseContext(), "Please enter a session title.",Toast.LENGTH_LONG).show();
}
}

///////////// Go to user page ///////////////////
//Go to user page when the zombie icon is clicked
public void goToUserPage(View view){
Intent goToUserPage = new Intent(this, UserProfile.class);
this.startActivity(goToUserPage.putExtra("playerId",playerId));
}

//////// TEST BUTTON /////
public void onTestyClick(View view) {
startActivity(new Intent(MainActivity.this, NotificationActivity.class));
}




// Direct users to sign in page
//Show the signin page if the player is not signed in when they open the app
private void signInUser() {
AWSMobileClient.getInstance().showSignIn(MainActivity.this,
// customize the built in sign in page
//Customize the built-in signin page with the defined theme color and icon
SignInUIOptions.builder().backgroundColor(16763080).logo(R.mipmap.ic_launcher_round).build(),
new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails result) {
Log.i(TAG, "successfully show signed in page");
Log.i(TAG, "Successfully show signed in page");
}

@Override
Expand All @@ -191,13 +186,13 @@ public void onError(Exception e) {
});
}

// sign out user and show them sign in page
//Sign out the player and show them the signin page
public void signoutCurrentUser(View view) {
AWSMobileClient.getInstance().signOut();
signInUser();
}

// onclick method for button to join existing game sessions
//onclick method for player to join an existing game session
@Override
public void joinExistingGameSession(ListSessionsQuery.Item session) {
Intent goToMapIntent = new Intent(this, MapsActivity.class);
Expand All @@ -206,43 +201,14 @@ public void joinExistingGameSession(ListSessionsQuery.Item session) {
this.startActivity(goToMapIntent);
}

// @Override
// public void addPlayerToChosenGame(final ListSessionsQuery.Item session) {
//// Query
// CreatePlayerInput playerInput = CreatePlayerInput.builder()
// .playerSessionId(session.id())
// .isIt(false)
// .lat(currentUserLocation.latitude)
// .lon(currentUserLocation.longitude)
// .username(AWSMobileClient.getInstance().getUsername())
// .build();
// CreatePlayerMutation createPlayerMutation = CreatePlayerMutation.builder().input(playerInput).build();
// awsAppSyncClient.mutate(createPlayerMutation).enqueue((new GraphQLCall.Callback<CreatePlayerMutation.Data>() {
// @Override
// public void onResponse(@Nonnull Response<CreatePlayerMutation.Data> response) {
// String userID = response.data().createPlayer().id();
// Log.i(TAG, "player mutation happened! ... inside of a session mutation");
// Intent goToMapIntent = new Intent(MainActivity.this, MapsActivity.class);
// goToMapIntent.putExtra("sessionId", session.id());
// goToMapIntent.putExtra("userID", userID);
// Log.i("veach", session.id() + "\n" +userID);
// }
// @Override
// public void onFailure(@Nonnull ApolloException e) {
// Log.i(TAG, "mutation of player failed, boohoo!");
// }
// }));
// }

// get all sessions
//Get all sessions from the database
private void queryAllSessions() {
Log.i(TAG, "query all sessions");
awsAppSyncClient.query(ListSessionsQuery.builder().build())
.responseFetcher(AppSyncResponseFetchers.NETWORK_ONLY)
.enqueue(getAllSessionsCallBack);
}

// Callback to update the list of sessions and recycler view that displays them
//Callback to update the list of sessions and recycler view that displays them
private GraphQLCall.Callback<ListSessionsQuery.Data> getAllSessionsCallBack = new GraphQLCall.Callback<ListSessionsQuery.Data>() {
@Override
public void onResponse(@Nonnull final Response<ListSessionsQuery.Data> response) {
Expand All @@ -264,9 +230,8 @@ public void onFailure(@Nonnull ApolloException e) {
}
};

// get current user location
//Get current player location
private void getCurrentUserLocation() {
Log.i(TAG, "called getCurrentUserLocation");
fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(final Location location) {
Expand All @@ -277,7 +242,6 @@ public void onSuccess(final Location location) {
public void run() {
currentUserLocation = new LatLng(location.getLatitude(), location.getLongitude());
queryAllSessions();
Log.i(TAG, "playerId in getcurrentUserlocation " + playerId);
if (playerId == null) {
createPlayer();
}
Expand All @@ -293,21 +257,17 @@ public void onFailure(@NonNull Exception e) {
});
}

// TODO: Build onDestroy that deletes user data from DB


//Check if the player's username is already in the database
private void checkIfPlayerAlreadyExistInDatabase() {
awsAppSyncClient.query(ListPlayersQuery.builder().build())
.responseFetcher(AppSyncResponseFetchers.NETWORK_ONLY)
.enqueue(new GraphQLCall.Callback<ListPlayersQuery.Data>() {
@Override
public void onResponse(@Nonnull Response<ListPlayersQuery.Data> response) {
Log.i(TAG, "this is playerID " + playerId);
String playerName = AWSMobileClient.getInstance().getUsername();
List<ListPlayersQuery.Item> players = response.data().listPlayers().items();
for(ListPlayersQuery.Item player : players){
if(player.username().equals(playerName)){
Log.i(TAG, "Username match " + playerName + " " + player.id());
playerId = player.id();
getCurrentUserLocation();
return;
Expand All @@ -318,12 +278,12 @@ public void onResponse(@Nonnull Response<ListPlayersQuery.Data> response) {

@Override
public void onFailure(@Nonnull ApolloException e) {
Log.e(TAG, "error in checking if a player already exists in database");
Log.e(TAG, "Error in checking if a player already exists in database");
}
});
}

// Make a Player
//Make a new player using their location, username, and start them as not it (human)
private void createPlayer() {
CreatePlayerInput input = CreatePlayerInput.builder()
.lat(currentUserLocation.latitude)
Expand All @@ -336,25 +296,24 @@ private void createPlayer() {
awsAppSyncClient.mutate(createPlayerMutation).enqueue(new GraphQLCall.Callback<CreatePlayerMutation.Data>() {
@Override
public void onResponse(@Nonnull Response<CreatePlayerMutation.Data> response) {

playerId = response.data().createPlayer().id();
Log.i(TAG, "created a player"+ playerId);

}

@Override
public void onFailure(@Nonnull ApolloException e) {
Log.e(TAG, "error in creating new player");
Log.e(TAG, "Error in creating new player");
}
});
}

// Checks if Gps Location is turned on or not on the user's phone
//Checks if GPS Location is turned on or not on the user's phone
private boolean checkGpsStatus() {
locationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

//Prompt the player that their GPS is not enabled and to turn it on to play
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled, do you want to enable it?")
Expand All @@ -373,7 +332,7 @@ public void onClick(final DialogInterface dialog, final int id) {
alert.show();
}

// filter out list of sessions to a smaller list that consist of sessions nearby the player's location
//Filter the sessions fed to the recyclerView so the player only sees games within a defined distance from their location
private List<ListSessionsQuery.Item> filterSessionsBasedOnDistance(List<ListSessionsQuery.Item> allSessions) {
List<ListSessionsQuery.Item> filteredSessions = new LinkedList<>();
for (ListSessionsQuery.Item session : allSessions) {
Expand All @@ -387,4 +346,8 @@ private List<ListSessionsQuery.Item> filterSessionsBasedOnDistance(List<ListSess
}
return filteredSessions;
}

//TODO: Build onDestroy that deletes user data from DB
//TODO: Need to remove the player marker when they close the app so they don't keep showing up in the game session after they think they've left
//TODO: Add subscription to recyclerView
}
Loading