package com.lloydm.geosword.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.view.SurfaceView;

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

import android.content.Intent;
import android.graphics.Color;

public class PreGameLobbyActivity extends StandardGameMenuActivity
{
     private final static String TAG = "com.lloydm.geosword.activities.PreGameLobbyActivity";
     private final static int UPDATETIMER = 0;
     private final static long TIMEOUT = 60000;
     private final static int DEADTERRITORY = -10000;

     private int gameid = -1;
     private int teamid = -1;
     private int playerid = -1;
     private int maxteams = 0;
     private volatile boolean goingback = true;
     private volatile boolean waiting = false;

     private UploadCompleteBroadcastReceiver enterreceiver;
     private Button btnenter;
     private RadioButton[] radios = null;
     private long exittime = 0;
     private TextView timeleft = null;

     private volatile boolean entering = false;

     // private TextView[] txtpcount = null;
     // private TextView[] txtfcount = null;
     // private TextView[] txtscore = null;
     private String[] teaminfo = null;
     private int[] territoryscore = null;

     @Override
     protected void onPause()
     {
                     super.onPause();
                     if (enterreceiver != null)
                     {
                                     unregisterReceiver(enterreceiver);
                     }
                     enterreceiver = null;
                     handler.removeCallbacksAndMessages(null);
                     if (isFinishing())
                     {
                                     if (goingback)
                                     {

                                                     onChangeActivity(0);
                                     }
                     }
     }

     @SuppressLint("InlinedApi")
     @Override
     protected void onResume()
     {
                     super.onResume();
                     exittime = System.currentTimeMillis() + TIMEOUT;
                     if (!worldcampaign)
                     {
                                     setreceiver();
                                     if (isloggedin() && loginstatuschanged())
                                     {
                                                     // get stuff again that was in setup...
                                                     int teamid = 0;
                                                     for (int i = 0; i < maxteams; i++)
                                                     {
                                                                     if (radios[i].isChecked())
                                                                     {
                                                                                     teamid = i + 1;
                                                                                     break;
                                                                     }
                                                     }
                                                     if (teamid == 0)
                                                     {
                                                                     // error should not allow the user to do this...
                                                                     newtoast("Please select a team first");
                                                                     return;
                                                     }
                                                     final int teamnumber = teamid;
                                                     waiting = true;
                                                     // at this point we need to disable the radio buttons....
                                                     runOnUiThread(new Runnable()
                                                     {

                                                                     @Override
                                                                     public void run()
                                                                     {
                                                                                     for (int i = 0; i < maxteams; i++)
                                                                                     {
                                                                                                     radios[i].setEnabled(false);
                                                                                     }

                                                                     }
                                                     })
;

                                                     Intent serviceintent = new Intent(PreGameLobbyActivity.this, UploadService.class);
                                                     if (Build.VERSION.SDK_INT >= 12)
                                                     {
                                                                     serviceintent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                                                     }
                                                     serviceintent.setAction("com.lloydm.geosword.common.UploadService.enterthewarzone");
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.enterthewarzone.gameid", gameid);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.enterthewarzone.teamid", teamnumber);
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.uniqueid", uid);
                                                     startService(serviceintent);

                                     }
                     }
                     handler.removeCallbacksAndMessages(null);
                     Message msg = new Message();
                     msg.what = UPDATETIMER;
                     handler.sendMessageDelayed(msg, 1000);
                     setuphelp(R.string.htt_enter, R.string.htxt_enter, R.string.htt_enter);
     }

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

     @Override
     public void setup()
     {
                     setContentView(R.layout.activity_pregamelobby);
                     mainview = (View) findViewById(R.layout.activity_pregamelobby);
                     bvidresid = R.raw.faction;
                     bvideolooped = true;
                     bvideo = (SurfaceView) findViewById(R.id.surfacevidfaction);

                     worldcampaign = getIntent().getBooleanExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.worldcampaign", false);

                     if (!worldcampaign)
                     {
                                     setreceiver();
                     }

                     gameid = getIntent().getIntExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.gameid", -1);
                     // if this still -1 then there is a big problem....we should exit....
                     if (gameid == -1 && worldcampaign == false)
                     {
                                     newtoast("Error - game not found - should not happen");
                                     finish();
                                     return;
                     }
                     exittime = System.currentTimeMillis() + TIMEOUT;

                     timeleft = (TextView) findViewById(R.id.timeremaining);
                     timeleft.setTypeface(font);
                     timeleft.setVisibility(View.INVISIBLE);
                     /*
                         * txtpcount = new TextView[8]; txtfcount = new TextView[8]; txtscore = new TextView[8];
                         */
                     /*
                         * txtpcount[0] = (TextView) findViewById(R.id.team1pcount); txtpcount[1] = (TextView) findViewById(R.id.team2pcount); txtpcount[2] = (TextView) findViewById(R.id.team3pcount); txtpcount[3] =
                         * (TextView) findViewById(R.id.team4pcount); txtpcount[4] = (TextView) findViewById(R.id.team5pcount); txtpcount[5] = (TextView) findViewById(R.id.team6pcount); txtpcount[6] = (TextView)
                         * findViewById(R.id.team7pcount); txtpcount[7] = (TextView) findViewById(R.id.team8pcount);
                         *
                         * txtfcount[0] = (TextView) findViewById(R.id.team1fcount); txtfcount[1] = (TextView) findViewById(R.id.team2fcount); txtfcount[2] = (TextView) findViewById(R.id.team3fcount); txtfcount[3] =
                         * (TextView) findViewById(R.id.team4fcount); txtfcount[4] = (TextView) findViewById(R.id.team5fcount); txtfcount[5] = (TextView) findViewById(R.id.team6fcount); txtfcount[6] = (TextView)
                         * findViewById(R.id.team7fcount); txtfcount[7] = (TextView) findViewById(R.id.team8fcount);
                         *
                         * txtscore[0] = (TextView) findViewById(R.id.team1territory); txtscore[1] = (TextView) findViewById(R.id.team2territory); txtscore[2] = (TextView) findViewById(R.id.team3territory);
                         * txtscore[3] = (TextView) findViewById(R.id.team4territory); txtscore[4] = (TextView) findViewById(R.id.team5territory); txtscore[5] = (TextView) findViewById(R.id.team6territory);
                         * txtscore[6] = (TextView) findViewById(R.id.team7territory); txtscore[7] = (TextView) findViewById(R.id.team8territory);
                         *
/

                     radios = new RadioButton[5];

                     radios[0] = (RadioButton) findViewById(R.id.team1);
                     radios[1] = (RadioButton) findViewById(R.id.team2);
                     radios[2] = (RadioButton) findViewById(R.id.team3);
                     radios[3] = (RadioButton) findViewById(R.id.team4);
                     radios[4] = (RadioButton) findViewById(R.id.team5);

                     for (int i = 0; i < 5; i++)
                     {
                                     radios[i].setTypeface(font);

                     }
                     radios[0].setTextColor(Color.RED);
                     radios[1].setTextColor(Color.CYAN);
                     radios[2].setTextColor(Color.YELLOW);
                     radios[3].setTextColor(Color.GREEN);
                     radios[4].setTextColor(Color.MAGENTA);

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

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

                     territoryscore = new int[8];

                     teaminfo = getIntent().getStringArrayExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.teaminfo");
                     if (teaminfo == null)
                     {
                                     newtoast("error team info empty");
                                     // error....should never happen..except during testing...
                     }
                     else
                     {
                                     int size = teaminfo.length;
                                     if (size > 5)
                                     {
                                                     size = 5;
                                     }
                                     for (int i = 0; i < size; i++)
                                     {

                                                     final String[] teamrowdata = teaminfo[i].split("\\|");
                                                     final String pcount = (teamrowdata[0]); // player count
                                                     // final String fcount = (teamrowdata[1]); // friend count
                                                     // final String tscore = (teamrowdata[2]); // territory score
                                                     territoryscore[i] = Integer.decode((teamrowdata[2]));
                                                     // -10000 -if game over for that territory....
                                                     final int inct = Integer.decode(teamrowdata[3]); // whether the
                                                                                                                                                                                                                                                         // team is
                                                                                                                                                                                                                                                         // active I
                                                                                                                                                                                                                                                         // think..
                                                     final int index = i;
                                                     if (index >= 0 && index < 5)
                                                     {
                                                                     runOnUiThread(new Runnable()
                                                                     {
                                                                                     @Override
                                                                                     public void run()
                                                                                     {
                                                                                                     if (inct == -1 || !pcount.equals("0"))

                                                                                                     {
                                                                                                                     radios[index].setVisibility(View.INVISIBLE);
                                                                                                                     /*
                                                                                                                         * txtpcount[index].setVisibility(View.INVISIBLE) ; txtfcount[index].setVisibility(View.INVISIBLE ); txtscore[index].setVisibility(View.INVISIBLE );
                                                                                                                         */
                                                                                                     }
                                                                                                     else
                                                                                                     {
                                                                                                                     maxteams = index + 1;
                                                                                                                     /*
                                                                                                                         * txtpcount[index].setText(pcount); txtfcount[index].setText(fcount); txtscore[index].setText(tscore);
                                                                                                                         *
/
                                                                                                                     if (territoryscore[index] <= DEADTERRITORY)
                                                                                                                     {
                                                                                                                                     radios[index].setEnabled(false);
                                                                                                                     }
                                                                                                                     else
                                                                                                                     {
                                                                                                                                     radios[index].setEnabled(true);
                                                                                                                     }
                                                                                                     }
                                                                                                     radios[index].invalidate();
                                                                                                     /*
                                                                                                         * txtpcount[index].invalidate(); txtfcount[index].invalidate(); txtscore[index].invalidate();
                                                                                                         *
/
                                                                                     }
                                                                     });
                                                     }
                                                     else
                                                     {
                                                                     newtoast("error 1");
                                                     }
                                     }
                     }
                     for (int i = 0; i < maxteams; i++)
                     {
                                     radios[i].setId(i);
                     }
                     btnenter = (Button) findViewById(R.id.enter);
                     btnenter.setOnClickListener(new View.OnClickListener()
                     {
                                     @SuppressLint("InlinedApi")

                                     @Override
                                     public void onClick(View v)
                                     {
                                                     if (waiting)
                                                     {
                                                                     newtoast("Please wait...connecting to database");
                                                                     return;
                                                     }
                                                     // okay so we should JOIN THE BATTLE!!!!! YAY!!
                                                     int teamid = 0;
                                                     for (int i = 0; i < maxteams; i++)
                                                     {
                                                                     if (radios[i].isChecked())
                                                                     {
                                                                                     teamid = i + 1;
                                                                                     break;
                                                                     }
                                                     }
                                                     if (teamid == 0)
                                                     {
                                                                     // error should not allow the user to do this...
                                                                     newtoast("Please select a team first");
                                                                     entering = false;
                                                                     return;
                                                     }
                                                     final int teamnumber = teamid;
                                                     waiting = true;
                                                     // at this point we need to disable the radio buttons....
                                                     runOnUiThread(new Runnable()
                                                     {

                                                                     @Override
                                                                     public void run()
                                                                     {
                                                                                     for (int i = 0; i < maxteams; i++)
                                                                                     {
                                                                                                     radios[i].setEnabled(false);
                                                                                     }

                                                                     }
                                                     })
;
                                                     if (worldcampaign)
                                                     {
                                                                     onChangeActivity(10 + teamnumber);
                                                     }
                                                     else
                                                     {
                                                                     Intent serviceintent = new Intent(PreGameLobbyActivity.this, UploadService.class);
                                                                     if (Build.VERSION.SDK_INT >= 12)
                                                                     {
                                                                                     serviceintent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                                                                     }
                                                                     serviceintent.setAction("com.lloydm.geosword.common.UploadService.enterthewarzone");
                                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.enterthewarzone.gameid", gameid);
                                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.enterthewarzone.teamid", teamnumber);
                                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.uniqueid", uid);
                                                                     startService(serviceintent);
                                                                     entering = true;
                                                     }
                                     }
                     });

                     handler = new MyHandler()
                     {
                                     public void handleMessage(Message msg)
                                     {
                                                     if (msg.what == UPDATETIMER)
                                                     {
                                                                     runOnUiThread(new Runnable()
                                                                     {
                                                                                     @Override
                                                                                     public void run()
                                                                                     {
                                                                                                     if (!entering)
                                                                                                     {
                                                                                                                     /*
                                                                                                                         * String timetext = "Time Left To Enter:"; long timeremaining = exittime - System.currentTimeMillis(); // timeremaining%=1000; timeremaining /= 1000; if (timeremaining
                                                                                                                         * > 60)
{ int minutes = (int) Math.floor((double) timeremaining / 60.0); timetext = timetext + minutes + ":"; timeremaining -= 60 * minutes; } else { timetext =
                                                                                                                         * timetext + "0" + ":"; } if (timeremaining < 10) { timetext = timetext + "0" + timeremaining; } else { timetext = timetext + timeremaining; }
                                                                                                                         * timeleft.setText(timetext); timeleft.invalidate();
                                                                                                                         *
/
                                                                                                     }
                                                                                                     else
                                                                                                     {
                                                                                                                     final String etext = "Entering game.....";
                                                                                                                     timeleft.setVisibility(View.VISIBLE);
                                                                                                                     timeleft.setText(etext);
                                                                                                                     timeleft.invalidate();
                                                                                                     }
                                                                                     }
                                                                     });
                                                     }
                                                     this.removeCallbacksAndMessages(null);
                                                     if (exittime - System.currentTimeMillis() > 0)
                                                     {
                                                                     Message msg2 = new Message();
                                                                     msg.what = UPDATETIMER;
                                                                     this.sendMessageDelayed(msg2, 1000);
                                                     }
                                                     else
                                                     {
                                                                     // removed this......not needed at all.....
                                                                     // server has removed this user from the game......
                                                                     // (automatically timed out.... - their session has expired
                                                                     // - have a grace period though of about 60 seconds in case
                                                                     // of delays with network....)
                                                                     // newtoast("Timeout reached - too long to decide, returning to menu");
                                                                     // handler.removeCallbacksAndMessages(null);
                                                                     // onChangeActivity(0);
                                                     }
                                     }
                     };
                     handler.removeCallbacksAndMessages(null);
                     Message msg = new Message();
                     msg.what = UPDATETIMER;
                     handler.sendMessageDelayed(msg, 1000);
                    
                     final int scount = Integer.decode(getprefs("com.lloydm.geosword.activities.PreGameLobbyActivity.scount", "0"));
                     saveprefs("com.lloydm.geosword.activities.PreGameLobbyActivity.scount",Integer.toString(scount+1));
                     switch(scount)
                     {
                                     case 3:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev1), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 4:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev2), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 6:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev3), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 7:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev4), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 10:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev5), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 16:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev6), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 20:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev7), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 24:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev8), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 32:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev9), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 40:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev10), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 50:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev11), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 60:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev12), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 80:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev13), Toast.LENGTH_LONG).show();
                                                     break;
                                     case 100:
                                                     Toast.makeText(PreGameLobbyActivity.this, getString(R.string.dev14), Toast.LENGTH_LONG).show();
                                                     break;
                                                    
                                     default:
                                                     break;
                     }
                    
     }

     private void setreceiver()
     {
                     if (enterreceiver == null)
                     {
                                     enterreceiver = new UploadCompleteBroadcastReceiver()
                                     {
                                                     @Override
                                                     public void onReceive(Context context, Intent intent)
                                                     {
                                                                     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");

                                                                     }

                                                                     waiting = false;
                                                                     runOnUiThread(new Runnable()
                                                                     {

                                                                                     @Override
                                                                                     public void run()
                                                                                     {
                                                                                                     for (int i = 0; i < maxteams; i++)
                                                                                                     {
                                                                                                                     radios[i].setEnabled(true);
                                                                                                     }

                                                                                     }
                                                                     })
;
                                                                     boolean result = intent.getBooleanExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.resultcode", false);
                                                                     if (result)
                                                                     {
                                                                                     // enter zee game....
                                                                                     teamid = intent.getIntExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.teamid", -1);
                                                                                     playerid = intent.getIntExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.playerid", -1);
                                                                                     Log.d(TAG, "PreGameLobby PlayerId in Receiver:" + playerid);
                                                                                     if (teamid == -1 && playerid == -1)
                                                                                     {
                                                                                                     final String goodteams = intent.getStringExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.teams");
                                                                                                     if (goodteams != null)
                                                                                                     {
                                                                                                                     if (goodteams.length() >= 5)
                                                                                                                     {
                                                                                                                                     runOnUiThread(new Runnable()
                                                                                                                                     {
                                                                                                                                                     @Override
                                                                                                                                                     public void run()
                                                                                                                                                     {
                                                                                                                                                                     for (int i = 0; i < 5; i++)
                                                                                                                                                                     {
                                                                                                                                                                                     if (goodteams.substring(i, i + 1).equals("0"))

                                                                                                                                                                                     {
                                                                                                                                                                                                     // team not available...
                                                                                                                                                                                                     radios[i].setVisibility(View.INVISIBLE);
                                                                                                                                                                                                     radios[i].setEnabled(false);
                                                                                                                                                                                     }
                                                                                                                                                                     }
                                                                                                                                                                     entering = false;
                                                                                                                                                     }
                                                                                                                                     });
                                                                                                                     }
                                                                                                     }
                                                                                     }
                                                                                     else
                                                                                     {
                                                                                                     onChangeActivity(1);
                                                                                     }
                                                                     }
                                                                     else
                                                                     {
                                                                                     int reason = intent.getIntExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.authenticationerror", -1);
                                                                                     if (reason == UploadService.LOGIN_NOT_FOUND)
                                                                                     {
                                                                                                     login();
                                                                                     }
                                                                                     reason = intent.getIntExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.failurereasoncode", -1);
                                                                                     if (reason == UploadService.JOINERROR_GAMEFULL)
                                                                                     {
                                                                                                     newtoast("Game has filled. Sorry - cannot enter this game now.");
                                                                                                     handler.removeCallbacksAndMessages(null);
                                                                                                     onChangeActivity(0);
                                                                                     }
                                                                                     if (reason == UploadService.JOINERROR_GAMEOVER)
                                                                                     {
                                                                                                     newtoast("Game has finished. Sorry - cannot enter this game now.");
                                                                                                     handler.removeCallbacksAndMessages(null);
                                                                                                     onChangeActivity(0);
                                                                                     }
                                                                     }
                                                     }
                                     };
                                     registerReceiver(enterreceiver, new IntentFilter("com.lloydm.geosword.activities.PreGameLobbyActivity.entergame"));
                     }
     }

     @Override
     public void onChangeActivity(int id)
     {
                     super.onChangeActivity(id);
                     if (id != 0 && id < 10)
                     {
                                     Log.d(TAG, "Entering game proper");
                                     goingback = false;
                                     startActivity(new Intent(this, InGameFrontMenuActivity.class).putExtra("com.lloydm.geosword.activities.InGameFrontMenuActivity.enterthewarzone.gameid", gameid).putExtra("com.lloydm.geosword.activities.InGameFrontMenuActivity.enterthewarzone.teamid", teamid).putExtra("com.lloydm.geosword.activities.InGameFrontMenuActivity.enterthewarzone.playerid", playerid));
                                     finish();
                     }
                     if (id == 0)
                     {
                                     startActivity(new Intent(this, MainMenuActivity.class));
                     }
                     if (id >= 10)
                     {
                                     goingback = false;
                                     startActivity(new Intent(this, InspectFleetActivity.class).putExtra("com.lloydm.geosword.common.UploadService.teamid", id - 10).putExtra("com.lloydm.geosword.activities.PreGameLobbyActivity.worldcampaign", true));
                                     finish();
                     }
     }
}