package sliz.elektromery;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import sliz.elektromery.R;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;


public class MenuActivity extends Activity implements OnItemSelectedListener
{
	private boolean bSet = false;
	
	Spinner spinner, spinner2, spinner3, spinner4; 
	private String mText = "";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
    	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
		WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); // (NEW)
    	
    	// Set context of app
    	appSettings.contextOfApplication = getApplicationContext();
    	appSettings appset = new appSettings();
    	
    	appset.loadSettings();
    	
    	PicActivity.selectedImagePath = "menu";
    	
    	setContentView(R.layout.menu_view);
    	
    	if (Build.VERSION.SDK_INT <19)createAppDirOLD();
    	if (Build.VERSION.SDK_INT >=19) createAppDir();
    	
    	createEvents();
    }
    
    
	@TargetApi(Build.VERSION_CODES.KITKAT)
	private void createAppDir()
    {
    	if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Log.d("Electrometer", "No SDCARD");
	    } else {
//	        File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Electrometer");
	    	File directory[] = this.getExternalFilesDirs(null);
	    	int indx = 1;
	        directory[indx].mkdirs();
	        boolean bDir = directory[indx].exists();
	        if(!bDir)
	        {
	        	indx = 0;
	        	bDir = directory[indx].mkdirs();
	        	bDir = directory[indx].exists();
	        }
	        
	        if(bDir)
	        {
		        appSettings.mAppDir = directory[indx];
		        
		     // Delete folder
		        File list[] = directory[indx].listFiles();
		        
		        for(int i = 0 ; i < list.length ; i++)
		        {
		        	list[i].delete();
		        	Log.d("Electrometer", list[i].toString() + " deleted.");
		        }
		        
		        // File path
		        appSettings.mAppDirFiles = new File(directory[indx].toString() + "/data");
		        bDir = appSettings.mAppDirFiles.mkdirs();
	        }
	    }
    }
	
	private void createAppDirOLD()
	{
		File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"sliz.elektromery");
		directory.mkdirs();
		
		appSettings.mAppDir = directory;
		
		// Delete folder
        File list[] = directory.listFiles();
        
        for(int i = 0 ; i < list.length ; i++)
        {
        	list[i].delete();
        	Log.d("Electrometer", list[i].toString() + " deleted.");
        }
        // File path
        appSettings.mAppDirFiles = new File(directory.toString() + "/data");
        appSettings.mAppDirFiles.mkdirs();
	}
    
    @Override
    protected void onDestroy() {
    	appSettings appset = new appSettings();
    	appset.saveSettings();
    	super.onDestroy();
    }
    
    private void createEvents()
    {
    	bSet = false;
    	// Bnt camera
    	Button btnCam = (Button)findViewById(R.id.btn_menu_open_cam);
    	btnCam.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Intent intnscnd = new Intent(MenuActivity.this, CamActivity.class);
	            startActivity(intnscnd);
	            MenuActivity.this.finish();
				
			}
		}
		);	
    	
    	// Bnt open pic
    	Button btnOpen = (Button)findViewById(R.id.btn_menu_open_pic);
    	btnOpen.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				PicActivity.selectedImagePath = null;
				PicActivity.bFromMenu = true;
				Intent intnscnd = new Intent(MenuActivity.this, PicActivity.class);
	            startActivity(intnscnd);
	            MenuActivity.this.finish();
			}
		}
		);
    	
    	// Bnt database
    	Button btnData = (Button)findViewById(R.id.btn_menu_database);
    	btnData.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Intent intnscnd = new Intent(MenuActivity.this, DatabaseActivity.class);
	            startActivity(intnscnd);
	            MenuActivity.this.finish();
			}
		}
		);
    	
    	// Bnt settings
    	Button btnSet = (Button)findViewById(R.id.btn_menu_settings);
    	btnSet.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				setContentView(R.layout.settings_view);
				createEventsSet();
				bSet = true;
			}
		}
		);
    	
    	// Bnt end
    	Button btnEnd = (Button)findViewById(R.id.btn_menu_end);
    	btnEnd.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				MenuActivity.this.finish();
			}
		}
		);
    	
    	// Init selected file if not selected
    	/// File spinner
    	if(appSettings.mSelectedFile == null)
    	{
	    	File files[] = appSettings.mAppDirFiles.listFiles();
	    	if(files != null)
	    	{
		    	if(files.length > 0)
		    	{
		    		appSettings.mSelectedFile = files[0].getName();
		    	}
	    	}
    	}
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
	    if(keyCode == KeyEvent.KEYCODE_BACK) 
	    {
	    	if(bSet)
	    	{
	    		setContentView(R.layout.menu_view);
		    	createEvents();
		    	return true;
	    	}
	    }
	    	
    	//Pass other events along their way up the chain
	    return super.onKeyDown(keyCode, event);
    }
    
    private void createEventsSet()
    {
    	// Bnt end
    	Button btnBack = (Button)findViewById(R.id.btn_set_back);
    	btnBack.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				setContentView(R.layout.menu_view);
		    	createEvents();
			}
		}
		);
    	
    	/// Set Frame segmentation method
    	spinner = (Spinner) findViewById(R.id.sp_frame_method);
    	// Create an ArrayAdapter using the string array and a default spinner layout
    	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
    	        R.array.frame_method, android.R.layout.simple_spinner_item);
    	// Specify the layout to use when the list of choices appears
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    	
    	// Apply the adapter to the spinner
    	spinner.setAdapter(adapter);
    	// Set actual selected
    	spinner.setSelection(appSettings.mFrameDetectMethod);
    	spinner.setOnItemSelectedListener(this);
    	
    	
    	/// Set Digit segmentation method
    	spinner2 = (Spinner) findViewById(R.id.sp_set_segdigit);
    	// Create an ArrayAdapter using the string array and a default spinner layout
    	ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
    	        R.array.set_segdigit, android.R.layout.simple_spinner_item);
    	// Specify the layout to use when the list of choices appears
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	// Apply the adapter to the spinner
    	spinner2.setAdapter(adapter2);
    	// Set actual selected
    	spinner2.setSelection(appSettings.mDigitDetectMethod);
    	spinner2.setOnItemSelectedListener(this);
    	
    	/// Set OCR method
    	spinner3 = (Spinner) findViewById(R.id.sp_set_ocr);
    	// Create an ArrayAdapter using the string array and a default spinner layout
    	ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this,
    	        R.array.set_ocr, android.R.layout.simple_spinner_item);
    	// Specify the layout to use when the list of choices appears
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	// Apply the adapter to the spinner
    	spinner3.setAdapter(adapter3);
    	// Set actual selected
    	spinner3.setSelection(appSettings.mOCRMethod);
    	spinner3.setOnItemSelectedListener(this);
    	
    	/// File spinner
    	File files[] = appSettings.mAppDirFiles.listFiles();
    	List<String> fileNames = new ArrayList<String>();
    	int id4 = 0;
    	for(int i = 0 ; i < files.length ; i++)
    	{
    		if(files[i].getPath().endsWith(".csv"))
    			fileNames.add(files[i].getName());
    		if(files[i].getName().equals(appSettings.mSelectedFile))
    			id4 = i;
    	}

    	spinner4 = (Spinner) findViewById(R.id.sp_set_file_name);
    	ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, fileNames);
    	adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	
    	spinner4.setAdapter(adapter4);
    	spinner4.setSelection(id4);
    	spinner4.setOnItemSelectedListener(this);
    	
    	// Bnt new file
    	Button btnFile = (Button)findViewById(R.id.btn_set_new_file);
    	btnFile.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// Get file name from user
				textDialog();
			}
		}
		);
    	
    	// Bnt new file
    	Button btnDelete = (Button)findViewById(R.id.btn_set_delete);
    	btnDelete.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// Ask to confirm 
				alertDialog();
				
				
				
			}
		}
		);
    }
    
    void alertDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	String strTitle = getString(R.string.strDelete) + " " + appSettings.mSelectedFile;
		builder.setTitle(strTitle);
		
		builder.setPositiveButton(R.string.strOK, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				File sadFile = new File(appSettings.mAppDirFiles + "/" + appSettings.mSelectedFile);
				sadFile.delete();
				// Actualize frames
				createEventsSet();
			}
		});
		
		builder.setNegativeButton(R.string.strCancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();				
			}
		});
		
		builder.show();
    }

    void textDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.strNewFile));

		// Set up the input
		final EditText input = new EditText(this);
		// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
		input.setInputType(InputType.TYPE_CLASS_TEXT);
		builder.setView(input);

		// Set up the buttons
		builder.setPositiveButton(R.string.strOK, new DialogInterface.OnClickListener() { 
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		        mText = input.getText().toString();
		        
		     // Create new file
				File newFile = new File(appSettings.mAppDirFiles + "/" + mText + ".csv");
				
				try {
					newFile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				// Actualize frames
				createEventsSet();
		    }
		});
		builder.setNegativeButton(R.string.strCancel, new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		        dialog.cancel();
		    }
		});

		builder.show();
    }
    
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		
		appSettings.mFrameDetectMethod = (int) spinner.getSelectedItemId();
		appSettings.mDigitDetectMethod = (int) spinner2.getSelectedItemId();
		appSettings.mOCRMethod = (int) spinner3.getSelectedItemId();
		
		if(spinner4.getAdapter().getCount() > 0)
			appSettings.mSelectedFile = spinner4.getSelectedItem().toString();
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
}
