package client.vars;

import java.lang.reflect.Field;

import client.gui.element.FieldCallback;
import client.gui.element.FieldAction;
import common.util.CharValidator;
import common.util.Color;

public class StringVar extends BaseVar {
	public static interface StringFunction extends VarFunction {
		void apply(StringVar cv, String value);
	}
	
	private final StringFunction func;
	private final CharValidator validator;
	private final String def;
	private final int maxLength;
	private final boolean allowEmpty;
	
	public StringVar(String name, String display, Field field, Object object, CVarCategory category, int maxLength, StringFunction func, CharValidator validator, boolean allowEmpty) {
		super(name, display, field, object, category);
		this.func = func;
		this.maxLength = maxLength;
		this.validator = validator;
		this.allowEmpty = allowEmpty;
		try {
			this.def = (String)field.get(object);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	public String getType() {
		return Color.YELLOW + "float";
	}
	
	public boolean parse(String str) {
		if(this.validator != null)
			str = this.validator.filter(str);
		if(!this.allowEmpty && str.isEmpty())
			return false;
		if(str.length() > this.maxLength)
			str = str.substring(0, this.maxLength);
		try {
			this.field.set(this.object, str);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		if(this.func != null)
			this.func.apply(this, str);
		return true;
	}
	
	public String format() {
		try {
			return (String)this.field.get(this.object);
		}
		catch(IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	public String getDefault() {
		return this.def;
	}
	
	public client.gui.element.Field selector(int x, int y, int w, int h) {
		return new client.gui.element.Field(x, y, w, h, this.maxLength, new FieldCallback() {
			public void use(client.gui.element.Field elem, FieldAction value) {
				if(value == FieldAction.SEND || value == FieldAction.UNFOCUS) {
					if(!StringVar.this.allowEmpty && elem.getText().isEmpty())
						elem.setText(StringVar.this.format());
					else
						StringVar.this.parse(elem.getText());
				}
			}
		}, this.validator, this.format());
	}
}
