package com.lista1;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {

	private final String PATH = Environment.getExternalStorageDirectory()
			.toString();
	private final String FILENAME = "form_data.txt";
	private final int shift = 23;

	Button saveButton, clearButton, loadButton;
	EditText editPassword, editName, editEmail;
	RadioGroup genderRadioGroup;
	SeekBar brightnessSeekbar;
	RatingBar ratingBar;
	
	private boolean isAlertDialogVisible = false;
	
	private final String SHOW_WINDOW = "show_window";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		bindUiData();
		if(savedInstanceState!=null && savedInstanceState.containsKey(SHOW_WINDOW)){
			if(savedInstanceState.getBoolean(SHOW_WINDOW))
				createAlertDialog();
		}

	}

	private void bindUiData() {

		saveButton = (Button) findViewById(R.id.buttonSave);
		clearButton = (Button) findViewById(R.id.buttonClear);
		loadButton = (Button) findViewById(R.id.buttonLoad);
		editEmail = (EditText) findViewById(R.id.editEmail);
		editName = (EditText) findViewById(R.id.editName);
		editPassword = (EditText) findViewById(R.id.editPassword);
		genderRadioGroup = (RadioGroup) findViewById(R.id.radioGroupGender);
		brightnessSeekbar = (SeekBar) findViewById(R.id.seekBarBrightness);
		ratingBar = (RatingBar) findViewById(R.id.ratingBar1);

		loadButton.setOnClickListener(this);
		clearButton.setOnClickListener(this);
		saveButton.setOnClickListener(this);
		
		brightnessSeekbar.setOnSeekBarChangeListener(this);
		
		initializeBrightness();

	}

	private void initializeBrightness() {
		
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = (float) ((float)(brightnessSeekbar.getProgress())/100.0);
		getWindow().setAttributes(lp);
		
	}

	private void loadDefaultData() {

		editName.setText(R.string.nameDefault);
		editEmail.setText(R.string.emailDefault);
		editPassword.setText(R.string.passwordDefault);
		brightnessSeekbar.setProgress(getResources().getInteger(
				R.integer.brightness));
		ratingBar.setProgress(getResources().getInteger(R.integer.rating) * 2);
		genderRadioGroup.check(R.id.male);

	}

	private String serializeFormData() {
		StringBuilder builder = new StringBuilder();
		builder.append(R.id.editEmail);
		builder.append("&");
		builder.append(editEmail.getText().toString());
		builder.append("\n");
		builder.append(R.id.editName);
		builder.append("&");
		builder.append(editName.getText().toString());
		builder.append("\n");
		builder.append(R.id.editPassword);
		builder.append("&");
		builder.append(editPassword.getText().toString());
		builder.append("\n");
		builder.append(R.id.seekBarBrightness);
		builder.append("&");
		builder.append(brightnessSeekbar.getProgress());
		builder.append("\n");
		builder.append(R.id.ratingBar1);
		builder.append("&");
		builder.append(ratingBar.getRating());
		builder.append("\n");
		builder.append(R.id.radioGroupGender);
		builder.append("&");
		builder.append(genderRadioGroup.getCheckedRadioButtonId());
		builder.append("\n");
		return decode(builder.toString());
	}
	
	private String decode(String s){
		StringBuilder builder = new StringBuilder(s);
		for(int i=0; i<s.length(); i++)
			builder.setCharAt(i, (char)(builder.charAt(i)+shift));
		return builder.toString();
	}
	
	private String encode(String s){
		StringBuilder builder = new StringBuilder(s);
		for(int i=0; i<s.length(); i++)
			builder.setCharAt(i, (char)(builder.charAt(i)-shift));
		return builder.toString();
	}
	

	private void saveData() {
		String formData = serializeFormData();
		try {
			Log.e("Path:", PATH);
			File file = new File(PATH + File.separator + FILENAME);
			Writer output = new BufferedWriter(new FileWriter(file));
			output.write(formData);
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void createAlertDialog() {

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		TextView myMsg = new TextView(this);
		myMsg.setText("Are you sure?");
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		alertDialogBuilder.setView(myMsg);
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						saveData();
						isAlertDialogVisible = false;
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								isAlertDialogVisible = false;
							}
						});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
		isAlertDialogVisible = true;

	}

	private void loadData() {
		File file = new File(PATH+File.separator+FILENAME);
		if(!file.exists()){
			Toast toast = Toast.makeText(this, "Cannot load data. Text file doesn't exists", Toast.LENGTH_LONG);
			toast.show();
			return;
		}
		try {
			String form_data = deserializeString(file);
			String[] data = form_data.split("\n");
			editEmail.setText(data[0].split("&")[1]);
			editName.setText(data[1].split("&")[1]);
			editPassword.setText(data[2].split("&")[1]);
			brightnessSeekbar.setProgress(new Integer(data[3].split("&")[1]));
			float ratingProgress = new Float(data[4].split("&")[1]);
			ratingBar.setProgress((int)(ratingProgress*2));
			genderRadioGroup.check(new Integer(data[5].split("&")[1]));
		} catch (IOException e) {
			Toast toast = Toast.makeText(this, "Cannot load data. Something went wrong.", Toast.LENGTH_LONG);
			toast.show();
			return;
		}
	}

	public  String deserializeString(File file) throws IOException {
		int len;
		char[] chr = new char[4096];
		final StringBuffer buffer = new StringBuffer();
		final FileReader reader = new FileReader(file);
		try {
			while ((len = reader.read(chr)) > 0) {
				buffer.append(chr, 0, len);
			}
		} finally {
			reader.close();
		}
		return encode(buffer.toString());
	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.buttonClear:
			loadDefaultData();
			break;
		case R.id.buttonLoad:
			loadData();
			break;
		case R.id.buttonSave:
			createAlertDialog();
			break;
		}

	}

	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = (float) ((float)(brightnessSeekbar.getProgress())/100.0);
		getWindow().setAttributes(lp);
		
	}

	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putBoolean(SHOW_WINDOW, isAlertDialogVisible);
	}

}
