package com.lloydm.geosword.activities;

import com.lloydm.geosword.common.StandardGameMenuActivity;
import com.lloydm.geosword.common.UploadCompleteBroadcastReceiver;
import com.lloydm.geosword.common.UploadService;
import com.lloydm.geosword1.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.view.SurfaceView;

public class CreateOnlineGameActivity extends StandardGameMenuActivity
{

     // design change....
     // friends only....so....exp not needed, game always private, number of
     // fleets is 1
     //
     // 22-Apr-2015....further change.....
     // multiplayer game is now invite only....
     //
     // When the user creates the game (and enters it) the server sends back a
     // message which gets used
     // to create an invite key. The invite key can then be sent to player.
     // Fairly simple.
     // So....the creator of the game receives a key...the file however doesn't
     // generate on their device until
     // they enter the game properly...?hmmm work this out....

     // game options that get set...pretty much number of players (human - only
     // for paid users), number of players (bots)(perhaps),
     // faction choice needs to be worked on a bit too.....

     // so the user who created the game has the option on the "ingamefrontmenu"
     // to invite others to join.
     // so the invitation process happens in "ingamefrontmenu" ahh

     // then when the invite is opened and accepted the system goes straight into
     // the ingamefront menu - no join game
     // option needed at all. (or perhaps to the lobby where they choose their
     // team with validation)

     // server changes:

     // creating a game is much the same...except no password needed (key is
     // generated instead)
     // this key is sent back to the user who created the game.

     // join game..no different either - (not really - password and game name is
     // supplied by the invite key instead)

     // so.....the only difference with the server is the sending of a key to the
     // user when the game is created....
     // that is it...

     // app changes:

     // remove password on creategame.
     // check for key on successful create and store on device.
     // when user has entered the game allow them to invite others - add a button
     // to the InGameFrontMenu
     // that means a new screen is need of sorts....
     // allow player to choose who to invite....(ie friends etc)
     // then send message through whichever means desired....basically passing
     // them the key file...
     // the key file is not an EP4 file...it is a KP4 file....(much the same
     // naming convention)
     // the key file simply stores the game name and game password. (doesn't even
     // need to be encrypted - yet)
     // very easy actually...

     // those who join still need an account (which may be a free account)
     // to create a game for multiplayer one person at least needs a paid
     // account...
     // the account is kind of tied ot the device - if the same account is used
     // all over the place then simply
     // ban the account....(and brick the device ha ah ah ah?)

     private EditText[] txtinput = new EditText[1];
     private Spinner[] spninput = new Spinner[4];
     private final static int MAXPLAYERS = 16;
     private UploadCompleteBroadcastReceiver uploadreceiver = null;

     private int gameid = -1;
     private String gamekey = "";
     private String gamename = "";

     private boolean singleplayer = false;
    
     private class MySpinnerData
     {
                     public int[] value;
                     public String[] txt;

                     public MySpinnerData(int[] val, String[] str)
                     {
                                     value = val;
                                     txt = str;
                     }
     }

     private boolean goingback = true;
     private boolean waiting = false;
     private ArrayAdapter<String> numteamsadapter = null;

     private MySpinnerData numteamsdata = null;

     // private int numberofteams = 2;

     private Button btngo = null;

     private Button btnskirmish = null;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
                     super.onCreate(savedInstanceState);
     }

     @Override
     public void setup()
     {
                     setContentView(R.layout.activity_createonlinegame);
                     mainview = (View) findViewById(R.layout.activity_createonlinegame);

                     bvideolooped = true;
                     bvidresid = R.raw.grnmov;
                     bvideo = (SurfaceView) findViewById(R.id.surfacevidcreategame);

                     setreceiver();

                     txtinput[0] = (EditText) findViewById(R.id.input_gamename);
                     txtinput[0].setTypeface(font);

                     spninput[3] = (Spinner) findViewById(R.id.input_numteams);
                     numteamsdata = new MySpinnerData(new int[] { 1, 2, 3, 4, 5 }, new String[] { "Single Player", "2 Teams", "3 Teams", "4 Teams", "5 Teams" });
                     numteamsadapter = new ArrayAdapter<String>(this, R.layout.geo_spinner_layout, R.id.geo_spinner_text2, numteamsdata.txt);

                     spninput[3].setAdapter(numteamsadapter);

                     btnback = (Button) findViewById(R.id.btnback2);
                     btnback.setOnClickListener(new View.OnClickListener()
                     {

                                     @Override
                                     public void onClick(View v)
                                     {
                                                     goingback = true;
                                                     finish();
                                     }
                     })
;

                     btnskirmish = (Button) findViewById(R.id.btn_skirmish);
                     btnskirmish.setTypeface(font);
                     btnskirmish.setOnClickListener(new View.OnClickListener()
                     {

                                     @Override
                                     public void onClick(View v)
                                     {
                                                     // go to lobby activity.......
                                                     onChangeActivity(9);
                                     }
                     })
;

                     btngo = (Button) findViewById(R.id.btn_create);
                     btngo.setOnClickListener(new View.OnClickListener()
                     {
                                     @SuppressLint("InlinedApi")

                                     @Override
                                     public void onClick(View v)
                                     {
                                                     // get the data from each component and then send the data to
                                                     // the server and open the new activity if successful.....
                                                     if (waiting)
                                                     {
                                                                     newtoast("Please wait....trying to talk to database");
                                                                     return;
                                                     }
                                                     int maxplayers = MAXPLAYERS;
                                                     int gameprivate = 1;
                                                     String gamename = "";
                                                     String gamepassword = "";
                                                     long enddate = 0;

                                                     int numteams = 0;
                                                     int numfleets = 1;
                                                     int minexp = 0;
                                                     int maxexp = 99999999;
                                                     try
                                                     {
                                                                     numteams = numteamsdata.value[spninput[3].getSelectedItemPosition()];
                                                                     // numberofteams = numteams;
                                                                     gamename = txtinput[0].getText().toString();
                                                                     CreateOnlineGameActivity.this.gamename = gamename;
                                                                     gamepassword = "dummypass";// txtinput[1].getText().toString();
                                                                     gameprivate = 1;
                                                                     enddate = 60;
                                                                     if (maxplayers < numteams)
                                                                     {
                                                                                     newtoast("Sorry - not enough players for the teams chosen!");
                                                                                     return;
                                                                     }
                                                                     if (gamepassword.equals(""))
                                                                     {
                                                                                     newtoast("Sorry - must specify password if game is private");
                                                                                     return;
                                                                     }
                                                                     if (gamename.equals(""))
                                                                     {
                                                                                     newtoast("Sorry - must specify a game name");
                                                                                     return;
                                                                     }
                                                                     if (maxplayers > MAXPLAYERS)
                                                                     {
                                                                                     newtoast("Too many players..");
                                                                                     return;
                                                                     }
                                                                     if (maxexp < minexp)
                                                                     {
                                                                                     newtoast("Experience settings are incorrect");
                                                                                     return;
                                                                     }
                                                     }
                                                     catch (Exception e)
                                                     {
                                                                     // error.....
                                                                     newtoast("Sorry - some of your inputs were invalid!");
                                                                     return;
                                                     }
                                                     waiting = true;
                                                     if(numteams==1)
                                                     {
                                                                     singleplayer = true;
                                                     }
                                                     else
                                                     {
                                                                     singleplayer = false;
                                                     }
                                                     // pass these values to a service...which handles our
                                                     // uploads.....
                                                     Intent serviceintent = new Intent(CreateOnlineGameActivity.this, UploadService.class);
                                                     if (Build.VERSION.SDK_INT >= 12)
                                                     {
                                                                     serviceintent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                                                     }
                                                     serviceintent.setAction("com.lloydm.geosword.common.UploadService.makenewgame");
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.numteams", numteams);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.numfleets", numfleets);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.minexp", minexp);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.maxexp", maxexp);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.maxplayers", maxplayers);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.gameprivate", gameprivate);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.enddate", enddate);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.gamename", gamename);
                                                     if (gameprivate == 1)
                                                     {
                                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.gamepassword", gamepassword);

                                                     }
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.uniqueid", uid);
                                                     startService(serviceintent);
                                                     newtoast("Uploading game data to server - please wait for a response....");
                                     }
                     });

     }

     @Override
     protected void onResume()
     {
                     super.onResume();
                     if (uploadreceiver == null)
                     {
                                     setreceiver();
                                     // possibility that we have just re-logged in....
                     }
                     setuphelp(R.string.htt_create, R.string.htxt_create, R.string.htt_create);
     }

     @Override
     protected void onPause()
     {
                     super.onPause();
                     if (uploadreceiver != null)
                     {
                                     unregisterReceiver(uploadreceiver);
                     }
                     uploadreceiver = null;
                     if (isFinishing())
                     {
                                     if (goingback)
                                     {
                                                     // we want to start the first main menu activity.....
                                                     onChangeActivity(1);
                                     }
                     }
     }

     @Override
     public void onChangeActivity(int id)
     {
                     super.onChangeActivity(id);
                     if (id == 0)
                     {
                                     String[] teaminfo = new String[8];
                                     for (int i = 0; i < 8; i++)
                                     {
                                                     if (i < 5) // edited - changed - this is where the error was occurring....same as web output now....
                                                     {
                                                                     teaminfo[i] = "0|0|8|1";
                                                     }
                                                     else
                                                     {
                                                                     teaminfo[i] = "0|0|8|-1";
                                                     }
                                     }
                                     startActivity(new Intent(this, PreGameLobbyActivity.class).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.gameid", gameid).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.teaminfo", teaminfo).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.gamekey", gamekey).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.gamename", CreateOnlineGameActivity.this.gamename));
                                     finish();
                     }
                     if (id == 9)
                     {
                                     String[] teaminfo = new String[8];
                                     for (int i = 0; i < 8; i++)
                                     {
                                                     if (i < 5) // edited - changed - this is where the error was occurring....same as web output now....
                                                     {
                                                                     teaminfo[i] = "0|0|8|1";
                                                     }
                                                     else
                                                     {
                                                                     teaminfo[i] = "0|0|8|-1";
                                                     }
                                     }
                                     goingback = false;
                                     startActivity(new Intent(this, PreGameLobbyActivity.class).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.teaminfo", teaminfo).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.worldcampaign", true));
                                     finish();
                     }
                     if (id == 1)
                     {
                                     startActivity(new Intent(this, MainMenuActivity.class));
                     }
     }

     private void setreceiver()
     {
                     uploadreceiver = new UploadCompleteBroadcastReceiver()
                     {
                                     @Override
                                     public void onReceive(Context context, Intent intent)
                                     {
                                                     // the intent will contain the response from the
                                                     // server.....either true or false....very simple - that's all
                                                     // we care
                                                     // about when we send information to the server...and possibly
                                                     // an error code...

                                                     boolean success = intent.getBooleanExtra("com.lloydm.geosword.activities.CreateOnlineGameActivity.resultcode", false);
                                                     long tuid = intent.getLongExtra("com.lloydm.geosword.common.UploadService.uniqueid", -1);
                                                     if (tuid != uid)
                                                     {
                                                                     // ignore this one and try again.....
                                                                     Log.i(TAG, "uid does not match");
                                                                     success = false;

                                                     }

                                                     final String createresult = intent.getStringExtra("com.lloydm.geosword.activities.CreateOnlineGameActivity.gameid");
                                                     if (createresult != null && success == true)
                                                     {
                                                                     if (createresult.contains(":"))
                                                                     {
                                                                                     try
                                                                                     {
                                                                                                     gameid = Integer.decode(createresult.substring(0, createresult.indexOf(":")));
                                                                                     }
                                                                                     catch (Exception efg)
                                                                                     {
                                                                                                     gameid = -1;
                                                                                     }
                                                                     }
                                                     }
                                                     if (success && gameid != -1)
                                                     {
                                                                     // uploaded successfully....therefore we should load the
                                                                     // next activity....
                                                                     // and finish this one......
                                                                     // we also want to store the gamekey.......which should be
                                                                     // present.....
                                                                     try
                                                                     {
                                                                                     gamekey = createresult.substring(createresult.indexOf(":") + 1);
                                                                                     Log.i(TAG, "game key ok");
                                                                                     // store the gamekey for this gameid in shared
                                                                                     // preferences.....only the owner does this../creator
                                                                                     if(singleplayer)
                                                                                     {
                                                                                                     gamekey = "";
                                                                                     }
                                                                                     saveprefs("com.lloydm.geosword.gamekey_" + gameid, gamekey);
                                                                                     saveprefs("com.lloydm.geosword.gamename_" + gameid, gamename);
                                                                     }
                                                                     catch (Exception fffe)
                                                                     {
                                                                                     gamekey = "invalid";
                                                                                     Log.i(TAG, "Invalid gamekey");
                                                                     }
                                                                     goingback = false;
                                                                     onChangeActivity(0);
                                                     }
                                                     else
                                                     {
                                                                     // failure...inform the user and stay here.....
                                                                     goingback = true;
                                                                     int reason = intent.getIntExtra("com.lloydm.geosword.activities.CreateOnlineGameActivity.authenticationerror", -1);
                                                                     if (reason == UploadService.LOGIN_NOT_FOUND)
                                                                     {
                                                                                     // show the authdialog.....
                                                                                     login();
                                                                     }
                                                                     else
                                                                     {
                                                                                     reason = intent.getIntExtra("com.lloydm.geosword.activities.CreateOnlineGameActivity.failurereasoncode", -1);
                                                                                     if (reason == UploadService.CREATEERROR_TOOMANY)
                                                                                     {
                                                                                                     newtoast("Warning - You have created too many games created in a short space of time.");
                                                                                     }
                                                                                     else
                                                                                     {
                                                                                                     newtoast("Something went wrong during the upload process.");
                                                                                     }
                                                                     }
                                                     }
                                                     // reset waiting flag.....
                                                     waiting = false;
                                     }
                     };
                     registerReceiver(uploadreceiver, new IntentFilter("com.lloydm.geosword.activities.CreateOnlineGameActivity.makenewgame"));

     }
}