package com.example.issm;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;


public class ISSM extends Activity implements OnClickListener
{
	private DoubleBuffer buff;
	private IssmJni issmNative;
	private String mapName;
	private String issmFolder;
	private int size;
    private GLSurfaceView mGLView;
	private FrameLayout frame;
	private VerticalSeekBar bar;
	private TextView value;
	private ColorMap colorMap;
	private int alpha;
	private final int MINIMUM = 90;
	private final int OFFSET = 10;
	private ViewFlipper viewflipper;
	private ProgressDialog dialog;
	private ColorBar colorBar;
	//------------------------------------------------------------------------------------------------    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_issm);
        this.initialize();         
    }
  //----------------------------------------------------------------------------------------------
    private void initialize()
    {
    	Bundle map = getIntent().getExtras();
        {
        	if(map!= null)
        	{
        		issmFolder = map.getString("pathToFile");
        	}
        }
    	alpha = MINIMUM + OFFSET;
    	frame = (FrameLayout)findViewById(R.id.frame);
    	viewflipper = (ViewFlipper) findViewById(R.id.flipper);
        this.bar  = (VerticalSeekBar) findViewById(R.id.seekbar);
        this.value  = (TextView) super.findViewById(R.id.value);
        Button solve = (Button) super.findViewById(R.id.solve);
        solve.setOnClickListener(this);
        Button back = (Button) super.findViewById(R.id.back);
        back.setOnClickListener(this);
        ImageButton gl = (ImageButton) findViewById(R.id.greenland);		
		gl.setOnClickListener(this);
		ImageButton art = (ImageButton) findViewById(R.id.antarctica);
		art.setOnClickListener(this);
        bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
        {
                public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser)
                {
	                	
                        alpha = progress + OFFSET;
                        value.setText("" + alpha + "%");
                }

	            @Override
	            public void onStartTrackingTouch(SeekBar seekBar) {}
	
	            @Override
	            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        //load up the ISSM library and create double buffer in java
        //which later on will be pass for native for allocation.
        issmNative = new IssmJni();
        
        //set default color map to be HSV
        this.colorMap = new ColorMap();
        //create colorBar
        colorBar = new ColorBar(this);
        colorBar.setColorMap(colorMap);
    }
//------------------------------------------------------------------------------------------------    
    public void createModel()
    {
		String solution_type="DiagnosticSolution";
    	String file = "";
    	if( mapName.equals("greenland"))
		{
    		file = "greenland";
		}
    	else file = "antarctica";

    	size = issmNative.createISSMModel(solution_type,issmFolder,file);
    	buff = ByteBuffer.allocateDirect(size*12*8).order(ByteOrder.nativeOrder()).asDoubleBuffer();
    }
//------------------------------------------------------------------------------------------------  
    public boolean onCreateOptionsMenu(Menu menu) 
    {
    	MenuInflater menuInflater = getMenuInflater();
    	menuInflater.inflate(R.menu.issm_menu,menu);
    	
    	return true;
    }
//------------------------------------------------------------------------------------------------  
    //Option Menu that allow user to choose color. 
   public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch (item.getItemId())
        {
	        case R.id.menu_about:          
	            Toast.makeText(ISSM.this, "ISSM Application", Toast.LENGTH_SHORT).show();
	            return true;
	 	            
	        case R.id.cl_autumn:
	        	colorMap.setAutumn(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        
	        case R.id.cl_bone:
	        	colorMap.setBone(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        
	        case R.id.cl_cool:
	        	colorMap.setCool(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_copper:
	        	colorMap.setCopper(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_gray:
	        	colorMap.setGray(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        
	        case R.id.cl_hot:
	        	colorMap.setGray(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        
	        case R.id.cl_hsv:
	        	colorMap.setDefault(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_jet:
	        	colorMap.setJet(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_pink:
	        	colorMap.setPink(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_spring:
	        	colorMap.setSpring(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_summer:	
	        	colorMap.setSummer(); colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        	
	        case R.id.cl_winter:
	        	colorMap.setWinter();colorBar.setColorMap(colorMap);
	        	drawFigure();
	        	return true;
	        default:
	        	return super.onOptionsItemSelected(item);
        }
    	
    }
//   
   
//---------------------------------------------------------------------------------   
    public void onClick(View view) 
	{
    	switch(view.getId())
    	{
	    	case R.id.greenland:
			{
				mapName= "greenland";
				viewflipper.setInAnimation(inFromRightAnimation());
		        viewflipper.setOutAnimation(outToLeftAnimation());
		        viewflipper.showNext();
		        //create FemModel in native code and return the size of the model
		        this.createModel();
		        break;
			}
	    	case R.id.antarctica:
			{
				mapName= "antarctica";
				viewflipper.setInAnimation(inFromRightAnimation());
		        viewflipper.setOutAnimation(outToLeftAnimation());
		        viewflipper.showNext();
		        //create FemModel in native code and return the size of the model
		        this.createModel();
		        break;
			}
	    	case R.id.back:
	    	{
	    		 frame.removeView(mGLView);
	    		 viewflipper.setInAnimation(inFromLeftAnimation());
		         viewflipper.setOutAnimation(outToRightAnimation());
		         viewflipper.showPrevious(); 
		         break;
	    	}
    		case R.id.solve:
    		{
    			dialog = new ProgressDialog(view.getContext());
    			dialog.setCancelable(true);
    			dialog.setMessage("Loading View. Please Wait ...");
    			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    			dialog.setProgress(0);
    			dialog.setMax(100);
    			new CalculationTask().execute(alpha);
    			break;
    		}
    	}
	}
//---------------------------------------------------------------------------------- 
    public void drawFigure()
    {
    	frame.removeAllViews();
    	mGLView = new MyGLSurfaceView(this, buff, size, colorMap);
    	frame.addView(mGLView);
    	//frame.addView(colorBar);
    }
//------------------------------------------------------------------------------------
   //AsyncTask will allow to display while doing some task in the background
   private class CalculationTask extends AsyncTask<Integer,Integer,Boolean>
   {
		@Override
		protected Boolean doInBackground(Integer... target) 
		{
			Thread thread = new Thread()
			{
				public void run()
				{
					for(int i = 0; i <= 100; i+=5)
					{
						try {
							Thread.sleep(300);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						publishProgress(i);
					}
				}
			};
			thread.start();
			issmNative.solveISSMModel(target[0],buff);
			return true;
		}
		
		protected void onPreExecute()
		{
			super.onPostExecute(null);
			dialog.show();
		}
		protected void onProgressUpdate(Integer ... value)
		{
			super.onProgressUpdate();
			dialog.setProgress(value[0]);
		}
		protected void onPostExecute(Boolean result)
		{
			super.onPostExecute(result);
			dialog.dismiss();
			if(result) drawFigure();
		}
	   
   }
//----------------------------------------------------------------------------------- 
    
    // Below are implementation for the animation between map selection and core computation

	private Animation inFromRightAnimation() {

	Animation inFromRight = new TranslateAnimation(
	Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
	Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
	);
	inFromRight.setDuration(500);
	inFromRight.setInterpolator(new AccelerateInterpolator());
	return inFromRight;
	}
	private Animation outToLeftAnimation() {
	Animation outtoLeft = new TranslateAnimation(
	  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
	  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
	);
	outtoLeft.setDuration(500);
	outtoLeft.setInterpolator(new AccelerateInterpolator());
	return outtoLeft;
	}

	private Animation inFromLeftAnimation() {
	Animation inFromLeft = new TranslateAnimation(
	Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
	Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
	);
	inFromLeft.setDuration(500);
	inFromLeft.setInterpolator(new AccelerateInterpolator());
	return inFromLeft;
	}
	private Animation outToRightAnimation() {
	Animation outtoRight = new TranslateAnimation(
	  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
	  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
	);
	outtoRight.setDuration(500);
	outtoRight.setInterpolator(new AccelerateInterpolator());
	return outtoRight;
	}
//-------------------------------------------------------------------------------------------	 
}
/////////////////////////////////////////////////////////////////////////////////////////////