package client.vars;

import java.lang.reflect.Field;

import client.gui.Style;
import client.gui.element.FieldCallback;
import client.gui.element.Label;
import client.gui.element.Slider;
import client.gui.element.FieldAction;
import common.util.Color;
import common.util.Util;

public class ColorVar extends IntVar {
	private final boolean alpha;
	
	public ColorVar(String name, String display, Field field, Object object, CVarCategory category, boolean alpha, IntFunction func) {
		super(name, display, field, object, category, Integer.MIN_VALUE, Integer.MAX_VALUE, func, null, 0);
		this.alpha = alpha;
	}

	public String getType() {
		return this.alpha ? (Color.GRAY + "color32") : (Color.LIGHT_GRAY + "color");
	}
	
	protected Integer parseValue(String str) {
		if(str.length() != (this.alpha ? 8 : 6))
			return null;
		Integer value = Util.parseInt(str, -16);
		if(value == null)
			return null;
		return this.alpha || (value & 0xff000000) == 0 ? (this.alpha ? value : (0xff000000 | value)) : null;
	}
	
	protected String formatValue(int value) {
		return String.format(this.alpha ? "%08x" : "%06x", this.alpha ? value : (value & 0x00ffffff));
	}
	
	public Slider selector(int x, int y, int w, int h) {
		throw new UnsupportedOperationException("Kann keinen Schieberegler für Farben erstellen");
	}
	
	public Label label(int x, int y, int w) {
		return new Label(x, y, w, this.display);
	}
	
	public client.gui.element.Field editor(int x, int y, int w, int h) {
		return new client.gui.element.Field(x, y, w, h, this.alpha ? 8 : 6, new FieldCallback() {
			public void use(client.gui.element.Field elem, FieldAction value) {
				if(value == FieldAction.SEND || value == FieldAction.UNFOCUS) {
					if(!ColorVar.this.parse(elem.getText()))
						elem.setText(ColorVar.this.format());
				}
				else if(value == FieldAction.FUNCTION) {
					ColorVar.this.parse(ColorVar.this.getDefault());
					elem.setText(ColorVar.this.format());
				}
			}
		}, this.format());
	}
	
	public String getFieldValue(Style style) {
		try {
			return this.formatValue(this.field.getInt(style));
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}
