package com.danitheskunk.skunkworks;

import com.danitheskunk.skunkworks.gfx.Image;
import com.danitheskunk.skunkworks.gfx.NineSlice;
import com.danitheskunk.skunkworks.gfx.font.FontTTF;
import com.danitheskunk.skunkworks.gfx.font.FontTileset;
import com.danitheskunk.skunkworks.gfx.font.IFont;

abstract public class BaseWindow implements IWindow {
	protected final Engine engine;
	protected WindowStretchMode stretchMode;

	public BaseWindow(Engine engine) {
		this.engine = engine;
		stretchMode = WindowStretchMode.ASPECT;
	}

	@Override
	public Engine getEngine() {
		return engine;
	}

	@Override
	public IFont loadFontTTF(String path, float size) {
		var bytes = engine.loadBytes(path);

		return new FontTTF(bytes, size, this);
	}

	@Override
	public IFont loadFontTileset(String path) {
		var img = engine.loadImage(path);
		var charSize = Vec2i.div(img.getSize(), 16);
		var tex = loadTextureArray(img, charSize);
		assert tex.size() == 256;
		return new FontTileset(tex);
	}

	@Override
	public NineSlice loadNineSlice(Image image) {
		int x1 = -1;
		int x2 = -1;
		int y1 = -1;
		int y2 = -1;

		for(int i = 1; i < image.getWidth(); ++i) {
			if(image.getPixel(new Vec2i(i, 0)).getA() != 0) {
				x1 = i;
				break;
			}
		}
		for(int i = x1; i < image.getWidth(); ++i) {
			if(image.getPixel(new Vec2i(i, 0)).getA() == 0) {
				x2 = i;
				break;
			}
		}
		for(int i = 1; i < image.getHeight(); ++i) {
			if(image.getPixel(new Vec2i(0, i)).getA() != 0) {
				y1 = i;
				break;
			}
		}
		for(int i = y1; i < image.getHeight(); ++i) {
			if(image.getPixel(new Vec2i(i, 0)).getA() == 0) {
				y2 = i;
				break;
			}
		}

		if(x1 == -1 || x2 == -1 || y1 == -1 || y2 == -1) {
			throw new RuntimeException("NineSlice error");
		}
		var tl = image.getSubImage(new Recti(1, 1, x1 - 1, y1 - 1));
		var top = image.getSubImage(new Recti(x1, 1, x2 - x1, y1 - 1));
		var tr = image.getSubImage(new Recti(x2,
			1,
			image.getWidth() - x2,
			y1 - 1
		));
		var left = image.getSubImage(new Recti(1, y1, x1 - 1, y2 - y1));
		var center = image.getSubImage(new Recti(x1, y1, x2 - x1, y2 - y1));
		var right = image.getSubImage(new Recti(x2,
			y1,
			image.getWidth() - x2,
			y2 - y1
		));
		var bl = image.getSubImage(new Recti(1,
			y2,
			x1 - 1,
			image.getHeight() - y2
		));
		var bottom = image.getSubImage(new Recti(x1,
			y2,
			x2 - x1,
			image.getHeight() - y2
		));
		var br = image.getSubImage(new Recti(x2,
			y2,
			image.getWidth() - x2,
			image.getHeight() - y2
		));
		return new NineSlice(loadTexture(tl),
			loadTexture(tr),
			loadTexture(bl),
			loadTexture(br),
			loadTexture(top),
			loadTexture(right),
			loadTexture(bottom),
			loadTexture(left),
			loadTexture(center)
		);
	}

	@Override
	public NineSlice loadNineSlice(String path) {
		return loadNineSlice(engine.loadImage(path));
	}

	@Override
	public void setStretchMode(WindowStretchMode mode) {
		stretchMode = mode;
	}


}
