package client.vars;

import java.lang.reflect.Field;

import client.gui.element.Toggle;
import client.gui.element.ToggleCallback;
import common.util.Color;
import common.util.Util;

public class BoolVar extends BaseVar {
	public static interface BoolFunction extends VarFunction {
		void apply(BoolVar cv, boolean value);
	}

	private final BoolFunction func;
	private final boolean def;
	
	public BoolVar(String name, String display, Field field, Object object, CVarCategory category, BoolFunction func) {
		super(name, display, field, object, category);
		this.func = func;
		try {
			this.def = field.getBoolean(object);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	public String getType() {
		return Color.MAGENTA + "bool";
	}
	
	public boolean parse(String str) {
		Boolean value = Util.parseBoolean(str);
		if(value == null)
			return false;
		try {
			this.field.setBoolean(this.object, value);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		if(this.func != null)
			this.func.apply(this, value);
		return true;
	}
	
	public String format() {
		try {
			return "" + this.field.getBoolean(this.object);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	public String getDefault() {
		return "" + this.def;
	}
	
	public Toggle selector(int x, int y, int w, int h) {
		try {
			return new Toggle(x, y, w, h, this.def, this.field.getBoolean(this.object), new ToggleCallback() {
				public void use(Toggle elem, boolean value) {
					BoolVar.this.parse("" + value);
				}
			}, this.display);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}
