package com.yuji.ec;

import java.util.Calendar;

import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.yuji.ec.common.CommonUtil;
import com.yuji.ec.common.Constant;
import com.yuji.ec.db.NoteDao;
import com.yuji.ec.service.NoteUpdatorService;
import com.yuji.ec.utility.BaseActivity;
import com.yuji.ec.utility.DateUtil;
import com.yuji.ec.utility.Debug;
import com.yuji.ec.utility.EditPrefUtil;
import com.yuji.ec.utility.PasswordUtil;

public class SettingActivity extends BaseActivity {
	private EditPrefUtil pref = new EditPrefUtil(this);

	private LinearLayout messageLayout = null;
	private TextView messageView = null;
	private Button userButton = null;
	private Button noteButton = null;
	private Spinner sortSpinner = null;
	private RadioGroup sortRadioGroup = null;
	private RadioButton sortRadio1 = null;
	private RadioButton sortRadio2 = null;
	private CheckBox timeCheckBox = null;
	private LinearLayout timeLayout = null;
	private TextView timeView = null;
	private Button timeButton = null;
	private Button closeButton = null;

	private long updateTime = -1;
	private boolean isRegister = false;
	private boolean isBind = false;

	private class NoteUpdatorReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Toast toast = Toast.makeText(getApplicationContext(), "Time over!",
					Toast.LENGTH_LONG);
			toast.show();
		}
	}

	private NoteUpdatorService noteUpdatorService;
	private final NoteUpdatorReceiver receiver = new NoteUpdatorReceiver();

	private ServiceConnection serviceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			noteUpdatorService = ((NoteUpdatorService.KitchenTimerBinder) service)
					.getService();
		}

		public void onServiceDisconnected(ComponentName className) {
			noteUpdatorService = null;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);

		messageLayout = (LinearLayout) this.findViewById(R.id.settingLayout);
		messageView = (TextView) this.findViewById(R.id.settingMessage);
		userButton = (Button) this.findViewById(R.id.settingUserButton);
		noteButton = (Button) this.findViewById(R.id.settingNoteButton);
		sortSpinner = (Spinner) this.findViewById(R.id.settingSortSpinner);
		sortRadioGroup = (RadioGroup) this
				.findViewById(R.id.settingSortRadioGroup);
		sortRadio1 = (RadioButton) this.findViewById(R.id.settingSortRadio1);
		sortRadio2 = (RadioButton) this.findViewById(R.id.settingSortRadio2);
		timeCheckBox = (CheckBox) this.findViewById(R.id.settingTimeCheckBox);
		timeLayout = (LinearLayout) this.findViewById(R.id.settingTimeLayout);
		timeView = (TextView) this.findViewById(R.id.settingTimeText);
		timeButton = (Button) this.findViewById(R.id.settingTimeButton);

		closeButton = (Button) this.findViewById(R.id.settingCloseButton);

		userButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				userButtonOnClick();
			}
		});

		noteButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				noteButtonOnClick();
			}
		});

		sortSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				sortSpinnerItemSelected(parent, view, position, id);
			}

			public void onNothingSelected(AdapterView<?> view) {
				;
			}
		});
		sortRadio1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				sortCheckedChanged(buttonView, isChecked, 1);
			}
		});
		sortRadio2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				sortCheckedChanged(buttonView, isChecked, 2);
			}
		});
		timeCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				timeCheckBoxOnClick(buttonView, isChecked);
			}
		});
		timeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				timeButtonOnClick();
			}
		});
		closeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				closeButtonOnClick();
			}
		});

		ArrayAdapter<CharSequence> noteOrderAdapter = ArrayAdapter
				.createFromResource(this, R.array.note_order_array,
						android.R.layout.simple_spinner_item);
		noteOrderAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sortSpinner.setAdapter(noteOrderAdapter);

		setStatus();
	}

	@Override
	public void onStart() {
		super.onStart();

		int noteOrder = pref.getInt(Constant.PREF_NOTE_ORDER,
				Constant.NOTE_ORDER_CREATE);
		sortSpinner.setSelection(noteOrder);

		int orderBy = pref.getInt(Constant.PREF_NOTE_ORDER_BY,
				Constant.NOTE_ORDER_BY_ASC);
		switch (orderBy) {
		case Constant.NOTE_ORDER_BY_ASC:
			sortRadioGroup.check(sortRadio1.getId());
			break;
		case Constant.NOTE_ORDER_BY_DES:
			sortRadioGroup.check(sortRadio2.getId());
			break;
		}

		int autoUpdate = pref.getInt(Constant.PREF_AUTO_UPDATE, Constant.OFF);
		timeCheckBox.setChecked(autoUpdate == Constant.ON);

		updateTime = pref.getLong(Constant.PREF_UPDATE_TIME,
				DateUtil.getTime(0, 0, 0));
		String str = DateUtil.toDateString(SettingActivity.this, updateTime);
		timeView.setText(str);
	}

	@Override
	public void onPause() {
		int noteOrder = sortSpinner.getSelectedItemPosition();
		pref.put(Constant.PREF_NOTE_ORDER, noteOrder);

		int orderById = sortRadioGroup.getCheckedRadioButtonId();
		int orderBy = Constant.NOTE_ORDER_BY_ASC;
		if (orderById == sortRadio1.getId()) {
			orderBy = Constant.NOTE_ORDER_BY_ASC;
		} else if (orderById == sortRadio2.getId()) {
			orderBy = Constant.NOTE_ORDER_BY_DES;
		}
		pref.put(Constant.PREF_NOTE_ORDER_BY, orderBy);

		int autoUpdate = (timeCheckBox.isChecked()) ? Constant.ON
				: Constant.OFF;
		int prevAutoUpdate = pref.getInt(Constant.PREF_AUTO_UPDATE);
		long prevUpdateTime = pref.getLong(Constant.PREF_UPDATE_TIME);
		// 自動更新がON、時刻設定済みならば
		if (autoUpdate == Constant.ON) {
			if (updateTime >= 0) {
				// 自動更新がOFFからON、もしくは時刻が変更
				if (prevAutoUpdate == Constant.OFF
						|| prevUpdateTime != updateTime) {
					pref.put(Constant.PREF_UPDATE_TIME, updateTime);

					updateNote();
				}
			} else {
				autoUpdate = 0;
			}
		}
		if (prevAutoUpdate == Constant.ON && autoUpdate == Constant.OFF) {
			stopService();
		}
		pref.put(Constant.PREF_AUTO_UPDATE, autoUpdate);
		pref.update();

		if (isBind) {
			unbindService(serviceConnection); // バインド解除
			isBind = false;
		}
		if (isRegister) {
			unregisterReceiver(receiver); // 登録解除
			isRegister = false;
		}
		
		super.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	private void stopService() {
		NoteUpdatorService.stopService(this);
	}

	private void updateNote() {
		try {
			stopService();

			Intent intent = new Intent(this, NoteUpdatorService.class);
			intent.setAction(NoteUpdatorService.ACTION_START);
			startService(intent);
			IntentFilter filter = new IntentFilter(NoteUpdatorService.ACTION);
			registerReceiver(receiver, filter);
			isRegister = true;

			// サービスにバインド
			bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
			isBind = true;
		} catch (Exception e) {
			Debug.d(this, null, e);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode != KeyEvent.KEYCODE_BACK) {
			return super.onKeyDown(keyCode, event);
		} else {
			closeButtonOnClick();
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		setStatus();
	}

	private void userButtonOnClick() {
		Intent intent = new Intent(this, (Class<?>) UserPasswordActivity.class);
		startActivityForResult(intent, 0);
	}

	private void noteButtonOnClick() {
		NoteUpdatorActivity.init(this);
		Intent intent = new Intent(this, (Class<?>) NoteUpdatorActivity.class);
		startActivityForResult(intent, 0);
	}

	private void sortSpinnerItemSelected(AdapterView<?> parent, View view,
			int position, long id) {

	}

	private void sortCheckedChanged(CompoundButton buttonView,
			boolean isChecked, int i) {

	}

	protected void timeCheckBoxOnClick(CompoundButton buttonView,
			boolean isChecked) {
		if (isChecked) {

		} else {
			updateTime = -1;
		}

		setStatus();
	}

	private void timeButtonOnClick() {
		Calendar calendar = Calendar.getInstance();
		long t = updateTime;
		if (t < 0) {
			t = pref.getLong(Constant.PREF_UPDATE_TIME, -1);
		}
		if (t >= 0) {
			calendar.setTimeInMillis(t);
		}
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);

		TimePickerDialog timePickerDialog = new TimePickerDialog(this,
				new TimePickerDialog.OnTimeSetListener() {
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						int second = 0;

						long t = DateUtil.getTime(hourOfDay, minute, second);
						String str = DateUtil.toDateString(
								SettingActivity.this, t);

						updateTime = t;
						timeView.setText(str);

						updateTime = t;
					}
				}, hour, minute, true);
		timePickerDialog.show();
	}

	private void closeButtonOnClick() {
		Intent intent = new Intent();
		setResult(RESULT_OK, intent);
		finish();

		EverClipActivity.init(false);
	}

	private void setStatus() {
		timeLayout.setVisibility(timeCheckBox.isChecked() ? View.VISIBLE
				: View.GONE);

		String passwd = PasswordUtil.getPassword(this);
		if (CommonUtil.isNull(passwd)) {
			messageLayout.setVisibility(View.VISIBLE);
			messageView.setText(getString(R.string.settingConfirmUserMsg));
			noteButton.setEnabled(false);
			sortSpinner.setEnabled(false);
			sortRadio1.setEnabled(false);
			sortRadio2.setEnabled(false);
			timeCheckBox.setEnabled(false);
			timeButton.setEnabled(false);
			return;
		}

		NoteDao dao = (NoteDao) NoteDao.getInstance();
		if (dao.isEmpty()) {
			messageLayout.setVisibility(View.VISIBLE);
			messageView.setText(getString(R.string.settingConfirmNoteMsg));
			noteButton.setEnabled(true);
			sortSpinner.setEnabled(false);
			sortRadio1.setEnabled(false);
			sortRadio2.setEnabled(false);
			timeCheckBox.setEnabled(false);
			timeButton.setEnabled(false);
			return;
		}

		messageLayout.setVisibility(View.GONE);
		noteButton.setEnabled(true);
		sortSpinner.setEnabled(true);
		sortRadio1.setEnabled(true);
		sortRadio2.setEnabled(true);
		timeCheckBox.setEnabled(true);
		timeButton.setEnabled(true);
	}

	public static void init(Context context) {

	}
}
