package org.pulpdust.da.timestamp;

import java.text.DateFormat;
import java.util.Date;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class TimeStampDaActivity extends FragmentActivity {
	final static String DA_EX_TEXT = "org.pulpdust.da.extra.TEXT";
	final static String DA_EX_THEME = "org.pulpdust.da.extra.THEME";
	final static String DA_EX_RETURN = "org.pulpdust.da.extra.RETURN";
	TextView dt;
	CheckBox dy;
	CheckBox tm;
	Button ok;
	DateFormat day;
	DateFormat time;
	Date date;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		int cs = getIntent().getIntExtra(DA_EX_THEME, 0);
		if (cs >= 1){
			setTheme(R.style.AppTheme_Dark);
		} else {
			setTheme(R.style.AppTheme);
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timestampda);
		dt = (TextView) findViewById(R.id.textView1);
		dy = (CheckBox) findViewById(R.id.checkBox1);
		tm = (CheckBox) findViewById(R.id.checkBox2);
		ok = (Button) findViewById(R.id.button1);
		readPrefs();
		day = DateFormat.getDateInstance(DateFormat.MEDIUM);
		time = DateFormat.getTimeInstance(DateFormat.SHORT);
		date = new Date();
		buildStamp(day, time, date);
		dy.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				buildStamp(day, time, date);
			}
			
		});
		tm.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				buildStamp(day, time, date);
			}
			
		});
		ok.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Intent ret = new Intent();
				ret.putExtra(DA_EX_RETURN, dt.getText().toString());
				setResult(RESULT_OK, ret);
				finish();
			}
			
		});
		
	}
	@Override
	protected void onStop(){
		super.onStop();
		writePrefs();
	}
	
	String buildStamp(DateFormat day, DateFormat time, Date date){
		String stamp;
		if (dy.isChecked() && !tm.isChecked()){
			stamp = day.format(date);
		} else if (!dy.isChecked() && tm.isChecked()){
			stamp = time.format(date);
		} else if (dy.isChecked() && tm.isChecked()){
			stamp = day.format(date) + " " + time.format(date);
		} else {
			stamp = "";
		}
		dt.setText(stamp);
		return stamp;
	}
	void readPrefs(){
		SharedPreferences sp = getPreferences(MODE_PRIVATE);
		dy.setChecked(sp.getBoolean("dy", true));
		tm.setChecked(sp.getBoolean("tm", true));
	}
	void writePrefs(){
		SharedPreferences sp = getPreferences(MODE_PRIVATE);
		SharedPreferences.Editor pe = sp.edit();
		pe.putBoolean("dy", dy.isChecked());
		pe.putBoolean("tm", tm.isChecked());
		pe.commit();
	}

}
