package client.gui.element;

import client.gui.Formatter;
import client.window.Button;
import common.util.Displayable;
import common.util.Util;

public class Switch<T> extends Element {
	private final SwitchCallback<T> func;
	private final T[] values;
	private final int def;
	
	private int value;

	public Switch(int x, int y, int w, int h, T[] values, T def, T init, SwitchCallback<T> callback, Formatter<Switch<T>> formatter) {
		super(x, y, w, h, formatter);
		this.func = callback;
		this.values = values;
		this.def = Util.indexOfChecked(this.values, def);
		this.value = Util.indexOfChecked(this.values, init);
		this.formatText();
	}

	public Switch(int x, int y, int w, int h, T[] values, T def, T init, SwitchCallback<T> callback, final String text) {
		this(x, y, w, h, values, def, init, callback, new Formatter<Switch<T>>() {
			public String use(Switch<T> elem) {
				T value = elem.getValue();
				return String.format("%s: %s", text, value instanceof Displayable disp ? disp.getDisplay() : value.toString());
			}
		});
	}

	public T getValue() {
		return this.values[this.value];
	}

	public void setValue(T value) {
		this.value = Util.indexOfChecked(this.values, value);
	}
	
	public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) {
		int prev = this.value;
		this.value = (ctrl || (btn == Button.MOUSE_MIDDLE)) ? this.def : (this.value + ((shift || (btn == Button.MOUSE_RIGHT)) ? -1 : 1));
		this.value = (this.value == this.values.length) ? 0 : ((this.value == -1) ? (this.values.length - 1) : this.value);
		if(this.value != prev) {
			this.func.use(this, this.getValue());
			this.formatText();
			this.playSound();
		}
	}
}
