package com.lloydm.geosword.activities;

import java.io.File;

import com.lloydm.geosword.Input;
import com.lloydm.geosword.J3D;
import com.lloydm.geosword.common.Config;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class TestActivity extends Activity
{

     private J3D j3d;
     private AssetManager assets;
     private final static String TAG = "com.lloydm.geosword.activities.TestActivity";
     private final static int MSGTOUCHED = 1;
     private final static int MSGTOUCHMOVE = 2;
     private final static int MSGNOTTOUCHING = 3;

     private int gameid = -1;
     private int playerid = -1;
     private int teamid = -1;

     private String attname = "";
     private String defname = "";

     private int attplanet = -1;

     public static boolean capmovie = false;

     private final static int MSGLOADINGUPDATE = 4;

     private String rfile = null;
     private String erfile = null;
     private Handler handler;

     private boolean muteon = false;

     @SuppressLint({ "InlinedApi", "HandlerLeak", "NewApi" })
     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
                     super.onCreate(savedInstanceState);
                     System.gc();
                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

                     // work out if low spec device or not.....

                     // default.....
                     Config.ISLOWSPECDEVICE = false;
                     if (Runtime.getRuntime().maxMemory() < (1024 * 1024 * 360))
                     {
                                     Config.ISLOWSPECDEVICE = true;
                                     Log.w(TAG, "warning possibly low spec device");
                                     Toast.makeText(this, "Low Spec Device", Toast.LENGTH_SHORT).show();
                     }
                     else
                     {
                                     Log.w(TAG, "should be correct spec device");
                                     Toast.makeText(this, "Recommended Spec Device", Toast.LENGTH_SHORT).show();
                     }
                     SharedPreferences prefs = getSharedPreferences("com.lloydm.geosword.common.stdgameprefs", MODE_PRIVATE);
                     String audiostatus = prefs.getString("com.lloydm.geosword.toggleaudio", "1");
                     if (audiostatus.equals("1"))
                     {
                                     muteon = true;
                     }
                     // this particular activity we don't want to sleep.....
                     if (Build.VERSION.SDK_INT >= 18)
                     {
                                     try
                                     {
                                                     setImmersive(true);
                                     }
                                     catch (Exception e)
                                     {
                                                     Log.w(TAG, "Failed to set Immersive Mode");
                                     }
                     }
                     capmovie = false;
                     gameid = getIntent().getIntExtra("com.lloydm.geosword.common.UploadService.gameid", -1);
                     playerid = getIntent().getIntExtra("com.lloydm.geosword.common.UploadService.playerid", -1);
                     teamid = getIntent().getIntExtra("com.lloydm.geosword.common.UploadService.teamid", -1);
                     attplanet = getIntent().getIntExtra("com.lloydm.geosword.common.UploadService.attplanetid", -1);

                     attname = getIntent().getStringExtra("com.lloydm.geosword.common.UploadService.attname");
                     defname = getIntent().getStringExtra("com.lloydm.geosword.common.UploadService.defname");
                     if (attname == null)
                     {
                                     attname = "";
                     }
                     if (defname == null)
                     {
                                     defname = "";
                     }
                     Log.i(TAG, "TIME:" + System.currentTimeMillis());
                     assets = getAssets();

                     handler = new Handler()
                     {
                                     public void handleMessage(Message msg)
                                     {
                                                     switch (msg.what)
                                                     {
                                                     case MSGLOADINGUPDATE:

                                                                     break;
                                                     case MSGTOUCHED:
                                                                     if (j3d != null)
                                                                     {
                                                                                     if (j3d.currentlevel != null)
                                                                                     {
                                                                                                     // j3d.currentlevel.setframe = true;
                                                                                                     // j3d.currentlevel.setframex = Input.xpos;
                                                                                                     // j3d.currentlevel.setframey = Input.ypos;
                                                                                                     j3d.currentlevel.setframey = 1;
                                                                                                     Log.i(TAG, "Touched!");
                                                                                                     j3d.seekbarhidetime = System.currentTimeMillis() + 10000;
                                                                                     }
                                                                     }
                                                                     break;

                                                     case MSGTOUCHMOVE:
                                                                     if (j3d != null)
                                                                     {
                                                                                     if (j3d.currentlevel != null)
                                                                                     {
                                                                                                     // j3d.currentlevel.setframe = true;
                                                                                                     // j3d.currentlevel.setframex = Input.xpos;
                                                                                                     // j3d.currentlevel.setframey = Input.ypos;
                                                                                                     j3d.currentlevel.setframey = 1;
                                                                                                     j3d.seekbarhidetime = System.currentTimeMillis() + 10000;
                                                                                                     Log.i(TAG, "Moving fingers");
                                                                                     }
                                                                     }
                                                                     break;
                                                     case MSGNOTTOUCHING:
                                                                     if (j3d != null)
                                                                     {
                                                                                     if (j3d.currentlevel != null)
                                                                                     {
                                                                                                     // j3d.currentlevel.setframe = false;
                                                                                                     // j3d.currentlevel.setframex = Input.xpos;
                                                                                                     // j3d.currentlevel.setframey = Input.ypos;
                                                                                                     j3d.currentlevel.setframey = -1;
                                                                                                     Log.i(TAG, "Stopped touching");

                                                                                     }
                                                                     }

                                                                     break;

                                                     default:
                                                                     break;
                                                     }
                                     }
                     };

                     try
                     {
                                     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                                     {
                                                     Intent intent = getIntent();
                                                     String action = intent.getAction();

                                                     if (action.compareTo(Intent.ACTION_VIEW) == 0)
                                                     {
                                                                     String scheme = intent.getScheme();
                                                                     // ContentResolver resolver = getContentResolver();

                                                                     if (scheme.compareTo(ContentResolver.SCHEME_CONTENT) == 0)
                                                                     {
                                                                                     // Uri uri = intent.getData();
                                                                                     // String name = getContentName(resolver, uri);

                                                                                     // Toast.makeText(this, "Loading replay:"+name,
                                                                                     // Toast.LENGTH_SHORT).show();
                                                                                     /*
                                                                                         * Log.v(TAG , "Content intent detected: " + action + " : " + intent.getDataString() + " : " + intent.getType() + " : " + name); InputStream input = null; try { input =
                                                                                         * resolver.openInputStream(uri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String importfilepath =
                                                                                         * Environment.getExternalStorageDirectory ().getAbsolutePath()+"/convergence_replays/" + name;//"/sdcard/My Documents/" + name; if(input!=null) { InputStreamToFile(input,
                                                                                         * importfilepath)
; }
                                                                                         */
                                                                     }
                                                                     else
                                                                                     if (scheme.compareTo(ContentResolver.SCHEME_FILE) == 0)
                                                                                     {
                                                                                                     Uri uri = intent.getData();
                                                                                                     // String name = uri.getLastPathSegment();
                                                                                                     File fi = new File(uri.getPath());
                                                                                                     erfile = fi.getAbsolutePath();
                                                                                                     if (erfile.contains("getvid"))
                                                                                                     {
                                                                                                                     capmovie = true;
                                                                                                                     Toast.makeText(this, "Making recording of:" + erfile, Toast.LENGTH_SHORT).show();
                                                                                                     }
                                                                                                     else
                                                                                                     {
                                                                                                                     capmovie = false;
                                                                                                                     Toast.makeText(this, "Loading replay:" + erfile, Toast.LENGTH_SHORT).show();
                                                                                                     }
                                                                                                     /*
                                                                                                         * Log.v(TAG , "File intent detected: " + action + " : " + intent.getDataString() + " : " + intent.getType() + " : " + name); InputStream input=null; try { input =
                                                                                                         * resolver.openInputStream(uri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String importfilepath =
                                                                                                         * Environment.getExternalStorageDirectory ().getAbsolutePath()+"/convergence_replays/" + name;//"/sdcard/My Documents/" + name; if(input!=null) { InputStreamToFile(input,
                                                                                                         * importfilepath)
; }
                                                                                                         */

                                                                                     }
                                                                                     else
                                                                                                     if (scheme.compareTo("http") == 0)
                                                                                                     {
                                                                                                                     /*
                                                                                                                         * Uri uri = intent.getData(); Toast.makeText(this,uri.getPath (),Toast.LENGTH_SHORT).show();
                                                                                                                         *
                                                                                                                         * erfile = null;
                                                                                                                         *
/
                                                                                                     }
                                                                                                     else
                                                                                                                     if (scheme.compareTo("ftp") == 0)
                                                                                                                     {
                                                                                                                     }
                                                     }

                                     }
                     }
                     catch (Exception fffff)
                     {
                                     Log.e(TAG, "Oops something went wrong on passing the file in from the file browser!");
                     }
                     try
                     {
                                     rfile = getIntent().getStringExtra("com.lloydm.geosword.activities.TestActivity.replayfile");
                                     Log.i(TAG, "Rfile:" + rfile);
                     }
                     catch (Exception ee)
                     {
                                     rfile = null;
                     }

                     if (rfile == null)
                     {
                                     if (erfile != null)
                                     {
                                                     rfile = erfile;
                                                     Log.i(TAG, "Starting activity from file browser...ain't that great!");
                                     }
                     }

                     if (getIntent().getIntExtra("com.lloydm.geosword.activities.TestActivity.screenviewmode", 0) == 1)
                     {
                                     j3d = new J3D(assets, true);
                                     if (j3d.init3D(this))
                                     {

                                     }
                                     else
                                     {
                                                     // exit with error - could not initialise 3d scene....
                                                     Log.w(TAG, "Could not start 3d mode");
                                                     finish();
                                     }
                                     return; // go no further....
                     }

                     if (rfile == null)
                     {
                                     Log.w(TAG, " ----- NO FILE SENT TO TestActivity ------ EXITING");
                                     Toast.makeText(this, "Error - no file passed in", Toast.LENGTH_SHORT).show();
                                     finish();
                     }
                     else
                     {
                                     Log.i(TAG, "TIME:" + System.currentTimeMillis());
                                     j3d = new J3D(assets, rfile, attplanet, muteon, attname, defname);
                                     if (j3d.init3D(this))
                                     {
                                                     // set the background.......

                                                     if (handler != null)
                                                     {
                                                                     Message msg = new Message();
                                                                     msg.what = MSGLOADINGUPDATE;
                                                                     handler.sendMessageDelayed(msg, 4000);
                                                     }
                                                     j3d.setBackground();
                                                     // set up the seek bar....

                                     }
                                     else
                                     {
                                                     // exit with error - could not initialise 3d scene....
                                                     Log.w(TAG, "Could not start 3d mode");
                                                     finish();
                                     }
                     }
     }

     @Override
     protected void onPause()
     {
                     super.onPause();
                     handler.removeCallbacksAndMessages(null);
                     if (j3d != null)
                     {
                                     // end the music if there is any....
                                     if (j3d.musicplayer != null)
                                     {
                                                     j3d.musicplayer.release();
                                                     j3d.musicplayer = null;
                                     }
                                     // need to signal to end the loading if Level3 class is still loading.....
                                     if (j3d.currentlevel != null)
                                     {
                                                     j3d.currentlevel.jumpoutimmediately = true;
                                                     if (j3d.currentlevel.pchatter != null)
                                                     {
                                                                     j3d.currentlevel.pchatter.end();
                                                     }
                                     }
                                     j3d.Pause();
                     }
                     // if there was a game id involved then go back to the InGameFrontMenu......
                     if (gameid != -1 && playerid != -1 && teamid != -1)
                     {
                                     startActivity(new Intent(this, InGameFrontMenuActivity.class).putExtra("com.lloydm.geosword.common.UploadService.gameid", gameid).putExtra("com.lloydm.geosword.common.UploadService.playerid", playerid).putExtra("com.lloydm.geosword.common.UploadService.teamid", teamid));
                     }
                     else
                     {
                                     startActivity(new Intent(this, MainMenuActivity.class));
                     }
                     if (!isFinishing())
                     {
                                     finish(); // should go back to previous activity....whatever that
                                                                             // was...most likely launch attack.....
                     }
     }

     @SuppressLint("InlinedApi")

     @Override
     protected void onResume()
     {
                     super.onResume();
                     handler.removeCallbacksAndMessages(null);
                     if (Build.VERSION.SDK_INT >= 14)
                     {
                                     try
                                     {

                                                     View decorView = getWindow().getDecorView();
                                                     int uioptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
                                                     decorView.setSystemUiVisibility(uioptions);
                                     }
                                     catch (Exception e)
                                     {
                                                     Log.e(TAG, "Cannot remove status and navigation bars");
                                     }
                     }
                     try
                     {
                                     if (j3d != null)
                                     {
                                                     j3d.Resume();
                                                     Log.i(TAG, "init music in onresume");
                                                     j3d.initmusic();
                                     }
                     }
                     catch (Exception e)
                     {
                                     Log.e(TAG, "Error resuming j3d engine. This activity will finish.");
                                     finish(); // resume the previous activity.....
                     }
     }

     @Override
     protected void onStop()
     {
                     super.onStop();
     }

     public boolean onTouchEvent(MotionEvent me)
     {
                     if (me.getAction() == MotionEvent.ACTION_DOWN)
                     {

                                     Input.xpos = (me.getX());
                                     Input.ypos = (me.getY());
                                     Input.touched = true;
                                     Input.down = true;
                                     if (j3d != null)
                                     {
                                                     if (j3d.currentlevel != null)
                                                     {
                                                                     handler.removeMessages(MSGTOUCHED);
                                                                     handler.removeMessages(MSGTOUCHMOVE);
                                                                     Message msg = new Message();
                                                                     msg.what = MSGTOUCHED;

                                                                     handler.sendMessage(msg);

                                                     }
                                     }
                                     return true;
                     }
                     if (me.getAction() == MotionEvent.ACTION_UP)
                     {

                                     Input.xpos = -1;
                                     Input.ypos = -1;
                                     Input.touched = false;
                                     Input.down = false;
                                     if (j3d != null)
                                     {
                                                     if (j3d.currentlevel != null)
                                                     {
                                                                     handler.removeMessages(MSGTOUCHED);
                                                                     handler.removeMessages(MSGTOUCHMOVE);
                                                                     handler.removeMessages(MSGNOTTOUCHING);
                                                                     Message msg = new Message();
                                                                     msg.what = MSGNOTTOUCHING;
                                                                     handler.sendMessage(msg);

                                                     }
                                     }

                                     return true;
                     }
                     if (me.getAction() == MotionEvent.ACTION_MOVE)
                     {
                                     Input.xpos = (me.getX());
                                     Input.ypos = (me.getY());
                                     Input.touched = false;
                                     Input.down = true;
                                     if (j3d != null)
                                     {
                                                     if (j3d.currentlevel != null)
                                                     {
                                                                     handler.removeMessages(MSGTOUCHED);
                                                                     handler.removeMessages(MSGTOUCHMOVE);
                                                                     Message msg = new Message();
                                                                     msg.what = MSGTOUCHMOVE;
                                                                     handler.sendMessage(msg);
                                                     }
                                     }
                                     return true;
                     }
                     return super.onTouchEvent(me);
     }

}