package org.tizen.gwt.sample.raphaelpaint.client;

import static org.tizen.gwt.sample.raphaelpaint.client.Constants.COLOR_PICKER_INIT;
import static org.tizen.gwt.sample.raphaelpaint.client.Constants.COLOR_TEXT_BRIGHT;
import static org.tizen.gwt.sample.raphaelpaint.client.Constants.COLOR_TEXT_DARK;
import static org.tizen.gwt.sample.raphaelpaint.client.Constants.SELECTOR_BTN_PICKER_CLOSE;
import static org.tizen.gwt.sample.raphaelpaint.client.Constants.SELECTOR_COLOR_PICKER;
import static org.tizen.gwt.sample.raphaelpaint.client.Constants.SELECTOR_PICKER_OUTPUT;

import org.tizen.gwt.sample.raphaelpaint.client.overlay.ColorPicker;
import org.tizen.gwt.sample.raphaelpaint.client.overlay.JQuery;
import org.tizen.gwt.sample.raphaelpaint.client.overlay.JQueryEvent;
import org.tizen.gwt.sample.raphaelpaint.client.overlay.JQueryHandler;
import org.tizen.gwt.sample.raphaelpaint.client.overlay.Raphael;
import org.tizen.gwt.sample.raphaelpaint.client.overlay.RaphaelColor;
import org.tizen.gwt.sample.raphaelpaint.client.overlay.JQuery.Css;

import com.google.gwt.dom.client.Element;

public class MyColorPicker extends JQueryHandler implements ColorPicker.ChangeCallback {
	
	private final RaphaelPaint mRaphaelPaint;
	private final JQuery mElement;
	private final ColorPicker mPicker;
	private final JQuery mOutput;
	private final JQuery mButtonClose;
	
	public MyColorPicker(RaphaelPaint raphaelPaint) {
		mRaphaelPaint = raphaelPaint;
		mElement = JQuery.jQuery(SELECTOR_COLOR_PICKER);
		mPicker = ColorPicker.create(360, 160, 300, COLOR_PICKER_INIT, mElement.get(0));
		mElement.hide();
		mPicker.setChangeCallback(this);
		mOutput = JQuery.jQuery(SELECTOR_PICKER_OUTPUT).on(JQueryEvent.KEY_UP, this);
		mButtonClose = JQuery.jQuery(SELECTOR_BTN_PICKER_CLOSE).on(JQueryEvent.CLICK, this);
	}
	
	@Override
	public void onEvent(JQueryEvent event) {
		Element target = event.delegateTarget();
		if(target == mButtonClose.get(0)) {
			mRaphaelPaint.onPickerClose();
		}
		else if(target == mOutput.get(0)) {
			updateColor(mOutput.text().trim(), true);
		}
	}
	
	@Override
	public void onChange(String color) {
		updateColor(color, true);
	}
	
	public void show() {
		mElement.show();
	}
	
	public void hide() {
		mElement.hide();
	}
	
	public void setColor(String color) {
		updateColor(color, true);
	}
	
	private void updateColor(String color, boolean fireListener) {
		RaphaelColor clr = Raphael.createColor(color);
		String hexColor = clr.hex();
		mOutput.text(hexColor)
			.css(Css.BACKGROUND_COLOR, hexColor)
			.css(Css.COLOR, clr.brightness() < 0.5 ? 
					COLOR_TEXT_BRIGHT : COLOR_TEXT_DARK);
		mPicker.setColor(hexColor);
		if(fireListener) {
			mRaphaelPaint.changeColor(hexColor);
		}
	}
}