package speiger.src.coreengine.ui.gui.font.glyth;

import speiger.src.coreengine.math.MathUtils;
import speiger.src.coreengine.platform.graphics.api.core.GraphicsDevice;
import speiger.src.coreengine.platform.graphics.api.texture.Texture;
import speiger.src.coreengine.platform.graphics.api.texture.drawable.Drawable;
import speiger.src.coreengine.ui.gui.font.FontTexture;

public class MissingGlyth implements UnbakedGlyth {
	private static final int WIDTH = 15;
	private static final int HEIGHT = 28;
	float size;
	float oversample;
	float advance;
	float scale;
	int width;
	int height;
	Glyth cached;
	
	public MissingGlyth(float size, float oversample) {
		this.size = size;
		this.oversample = oversample;
		this.scale = (size * oversample) / HEIGHT;
		this.advance = WIDTH * (size / HEIGHT);
		this.width = (int)(WIDTH * scale);
		this.height = (int)(HEIGHT * scale * 0.5F);
	}
	
	public void cleanCache() {
		cached = null;
	}

	@Override
	public float advance() { return advance; }
	@Override
	public float kerning(int codepoint) { return 0; }
	@Override
	public Glyth bake(GlythBaker baker) {
		if(cached == null) {
			cached = baker.bake(new IGlythSheetInfo() {
				@Override
				public int width() { return width; }
				@Override
				public int height() { return height; }
				@Override
				public float yOffset() {
					return -height * 0.5F;
				}
				@Override
				public void upload(Texture texture, int x, int y) {
					Drawable drawable = new Drawable(FontTexture.formatByColor(false), width, (int)(height));
					draw(drawable);
					drawable.upload(GraphicsDevice.get().queue(), texture, x, y, 0, 0, width, height);
					drawable.close();
				}
				@Override
				public boolean isColored() { return false; }
				@Override
				public float oversample() { return oversample; }
			});
		}
		return cached;
	}
	
	private void draw(Drawable texture) {
		texture.fill(0, 0, width, height, 255);
		int offset = MathUtils.ceil(width / 5F);
		texture.fill(offset, offset, width - offset * 2, height - offset * 2, 0);
	}
}
