package projectEQ2440.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import projectEQ2440.QRcode.QRDecode;
import projectEQ2440.camera.Preview;
import projectEQ2440.main.R;

public class MainActivity extends Activity {
	
	private ProgressBar progBar;
	private TextView textView;
	
	private Saver saver;
	private Button buttonStartStop;
	private FrameLayout framePreview;
	
	private Preview preview;
	private QRDecode qrDecode;
	
	private SharedPreferences sharedPref;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		progBar = (ProgressBar) findViewById(R.id.progBar);
		textView = (TextView) findViewById(R.id.textOutput);
		
		saver = new Saver();
		sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		
		buttonStartStop = (Button) findViewById(R.id.buttonStartStop);
		framePreview = (FrameLayout) findViewById(R.id.preview);
		
		preview = new Preview(this);
		framePreview.addView(preview);
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		setQRDecode();

		preview.born();
		cleanCacheDir();
	}

	@Override
	public void onPause() {
		if (qrDecode != null) {
			qrDecode.kill();
			qrDecode = null;
		}
		
		preview.kill();
		cleanCacheDir();
		
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		saver.kill();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.option_menu, menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (qrDecode == null) return super.onOptionsItemSelected(item);
		if (qrDecode.isRunning()) return super.onOptionsItemSelected(item);
		
		switch (item.getItemId()) {
	
			case R.id.itemSetting :
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, SettingActivity.class);
				startActivityForResult(intent, 0);
				break;
			
			case R.id.itemBye :
				this.finish();
				break;
		}

		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
	}
	
	private void setQRDecode() {
		
		if (qrDecode != null) qrDecode.kill();
		qrDecode = new QRDecode(preview);
		
		clickStop();
		
		buttonStartStop.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (qrDecode == null) return;
				if (qrDecode.isRunning()) {
					qrDecode.stop();
					clickStop();
				} else {
					clickStart();
					
					if (sharedPref.getBoolean("flashMode", false)) qrDecode.setFlashOn();
					else qrDecode.setFlashOff();
					
					if (sharedPref.getBoolean("frameCheck", false)) qrDecode.setWithFrameCheck();
					else qrDecode.setWithoutFrameCheck();
					
					if (sharedPref.getBoolean("colorMode", false)) qrDecode.setPictureRGB();
					else qrDecode.setPictureBW();
					
					Log.i("rateCalculation", "Begin");
					qrDecode.start();
				}
			}
		});
		
		qrDecode.setQRDecodeCallback(new QRDecode.QRDecodeCallback() {
			
			@Override
			public void decodingFinished(byte[] finalMessage) {
				clickStop();
				Log.i("rateCalculation", "finish");
				saver.save(finalMessage);
			}
			
			@Override
			public void wrongFrame(byte[] data, int version) {
				if (data == null) Log.i("FrameReceived", "wrong, version : "+version+", null");
				else Log.i("FrameReceived", "wrong, version : "+version+", length : "+data.length);
			}
			
			@Override
			public void goodFrame(byte[] data, int length, int totalFrame, int frameNumber, int version) {
				if (data == null) Log.i("FrameReceived", "good, version : "+version+", "+frameNumber+"/"+totalFrame+", null, ");
				else Log.i("FrameReceived", "good, version : "+version+", "+frameNumber+"/"+totalFrame+", length : "+data.length);
			}
			
			@Override
			public void state(int totalFrame, int decodedFrame, int currentFrame) {
				if (totalFrame > 0) {
					progBar.setMax(totalFrame);
					progBar.setProgress(decodedFrame);
				}
			}

		});
	}
	
	private void clickStart() {
		runOnUiThread(new Runnable() {
			public void run() {
				buttonStartStop.setText(getString(R.string.buttonStop));
				progBar.setProgress(0);
				progBar.setMax(1);
				textView.setText("");
				progBar.setVisibility(View.VISIBLE);
			}
		});
	}
	
	private void clickStop() {
		runOnUiThread(new Runnable() {
			public void run() {
				buttonStartStop.setText(getString(R.string.buttonStart));
				progBar.setProgress(0);
				progBar.setMax(1);
				textView.setText(getText(R.string.ready));
				progBar.setVisibility(View.INVISIBLE);
			}
		});
	}
	
	private void cleanCacheDir() {
		File[] tmps = this.getExternalCacheDir().listFiles();
		if (tmps == null) return;
		
		for (int k=0; k<tmps.length; k++) {
			tmps[k].delete();
		}
	}
	
	public class Saver {

		private RelativeLayout visual;
		
		private EditText text;
		
		private Button ok;
		private Button cancel;
		
		private byte[] data;
		
		public Saver() {
			
			visual = (RelativeLayout) findViewById(R.id.saver);
			text = (EditText) findViewById(R.id.addressBar);
			ok = (Button) findViewById(R.id.buttonSaverOK);
			cancel = (Button) findViewById(R.id.buttonSaverCancel);
			
			ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(text.getWindowToken(), 0);
					
					try {
						
						File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+text.getText());
						FileOutputStream out = new FileOutputStream(file);
						out.write(data);
						out.close();
						
						textView.setText(data.length+"bytes saved");
						visual.setVisibility(View.GONE);
						
						text.setText("");
						data = null;
						
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				}
			});
			
			cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(text.getWindowToken(), 0);
					
					textView.setText(data.length+"bytes lost");
					visual.setVisibility(View.GONE);
					
					text.setText("");
					data = null;
				}
			});
			
		}
		
		public void kill() {
			visual = null;
			text = null;
			ok = null;
			cancel = null;
			data = null;
		}
		
		public void save(byte[] data) {
			
			if (data == null) this.data = new byte[0];
			else this.data = data;
			
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					text.setText("");
					visual.setVisibility(View.VISIBLE);
				}
			});
		}

	}
	
}
