package com.kurukurupapa.tryandroid.fw.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

/**
 * 色選択ダイアログ
 *
 * 元ネタ<br>
 * Y.A.M の 雑記帳: Android　ColorPickerDialog を作った
 * http://y-anz-m.blogspot.com/2010/05/androidcolorpickerdialog.html
 */
public class BoxHsvColorDialog extends AlertDialog {

	public interface OnColorChangedListener {
		public void onColorChanged(int color);
	}

	private static final int COLOR_VIEW_HEIGHT = 72;
	private static final int MARGIN = 5;
	private ColorView view;
	private BoxHsvColorPicker picker;

	public BoxHsvColorDialog(Context context) {
		super(context);

		view = new ColorView(getContext());

		picker = new BoxHsvColorPicker(getContext());
		picker.setOnColorListener(new BoxHsvColorPicker.OnColorListener() {
			public void onColorChanging(int color) {
				view.setBackgroundColor(color);
			}
			public void onColorChanged(int color) {
				view.setBackgroundColor(color);
			}
		});

		FrameLayout frameLayout = new FrameLayout(getContext());

		LinearLayout layout = new LinearLayout(getContext());
		layout.setOrientation(LinearLayout.VERTICAL);
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.FILL_PARENT,
				FrameLayout.LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL);
		layoutParams.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
		frameLayout.addView(layout, layoutParams);

		LinearLayout.LayoutParams viewParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT, COLOR_VIEW_HEIGHT,
				Gravity.CENTER_HORIZONTAL);
		viewParams.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
		layout.addView(view, viewParams);

		LinearLayout.LayoutParams pickerParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT,
				Gravity.CENTER_HORIZONTAL);
		pickerParams.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
		layout.addView(picker, pickerParams);

		setView(frameLayout);
	}

	public void setOkButton(final OnColorChangedListener listener) {
		setButton(getContext().getString(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						listener.onColorChanged(picker.getSelectColor());
					}
				});
	}

	public void setSelectColor(int color) {
		view.setBackgroundColor(color);
		picker.setSelectColor(color);
	}

}
