package main;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import ea.Figur;
import ea.internal.gra.PixelFeld;

public class PlayerSheetLoader {

	private static Figur[] player;

	private static final float SCALE_DIV = 1.5f;

	public PlayerSheetLoader() {
		try {
			BufferedImage sheet = ImageIO.read(Tile.class.getResourceAsStream("/res/images/player_sprite_sheet.png"));

			PixelFeld[][] sprites = new PixelFeld[9][];
			sprites[0] = new PixelFeld[5];
			sprites[1] = new PixelFeld[5];
			sprites[2] = new PixelFeld[8];
			sprites[3] = new PixelFeld[8];
			sprites[4] = new PixelFeld[7];
			sprites[5] = new PixelFeld[7];
			sprites[6] = new PixelFeld[6];
			sprites[7] = new PixelFeld[6];
			sprites[8] = new PixelFeld[7];

			loadSprites(sprites[0], 0, 64, 32, sheet, true);
			loadSprites(sprites[1], 0, 64, 32, sheet, false);
			loadSprites(sprites[2], 1, 64, 32, sheet, true);
			loadSprites(sprites[3], 1, 64, 32, sheet, false);
			loadSprites(sprites[4], 2, 64, 32, sheet, true);
			loadSprites(sprites[5], 2, 64, 32, sheet, false);
			loadSprites(sprites[6], 3, 64, 32, sheet, true);
			loadSprites(sprites[7], 3, 64, 32, sheet, false);
			loadSprites(sprites[8], 7, 64, 32, sheet, false);

			Figur fig;
			player = new Figur[9];
			for (int i = 0; i < player.length; i++) {
				fig = new Figur();
				fig.animationSetzen(sprites[i]);
				player[i] = fig;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Figur getPlayer(int y) {
		return player[y];
	}

	private void loadSprites(PixelFeld[] sprites, int row, int w, int h, BufferedImage sheet, boolean reverse) {
		for (int s = 0; s < sprites.length; s++) {
			sprites[s] = new PixelFeld(w * (int) (World.SCALE / SCALE_DIV), h * (int) (World.SCALE / SCALE_DIV), 1);
			for (int x = 0; x < w; x++) {
				for (int y = 0; y < h; y++) {
					Color clr = new Color(sheet.getRGB((s * w + x), (row * h + y)), true);
					if (clr.getAlpha() > 0) {
						for (int i = 0; i < World.SCALE / SCALE_DIV; i++) {
							for (int j = 0; j < World.SCALE / SCALE_DIV; j++) {
								sprites[s].farbeSetzen(x * (int) (World.SCALE / SCALE_DIV) + i, y * (int) (World.SCALE / SCALE_DIV) + j, clr);
							}
						}
					}
				}
			}
			if (reverse) {
				PixelFeld copy = new PixelFeld(sprites[s].breite(), sprites[s].hoehe(), 1);
				for (int x = 0; x < sprites[s].breite(); x++) {
					for (int y = 0; y < sprites[s].hoehe(); y++) {
						copy.farbeSetzen(sprites[s].breite() - x - 1, y, sprites[s].getPic()[x][y]);
					}
				}
				sprites[s] = copy;
			}
		}
	}
}
