package com.pesets.idle.scenes.ui;

import java.util.ArrayList;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.pesets.game.Player;
import com.pesets.game.skills.Skill;
import com.pesets.resources.TextureGenerator;

public class SkillBar extends Window {
	private static final int CellSize = 40;
	private static final int IconSize = 32;
	
	Player player;
	ShapeRenderer shaper = new ShapeRenderer();

	public SkillBar(Skin skin, Player player) {
		super(skin);
		this.player = player;
		
		height = CellSize + 20;
		width = 200;
	}
	
	
	public void drawSkill(Skill skill, float x, float y, SpriteBatch batch)
	{
		batch.draw(TextureGenerator.getInstance().getSkillIcon(skill.getIcon()), x, y);
	}
	
	public void drawColdownMask(Skill skill, float x, float y, ShapeRenderer shaper)
	{
		float height = 0;
		if (skill.getCd() > 0)
		{
			height = skill.getCd() * IconSize / skill.getMaxColdown();
		}
		
		if (height > 0)
		{
			shaper.filledRect(x, y, IconSize, height);
		}
	}
	
	@Override
	public void draw(SpriteBatch batch, float parentAlpha) {
		super.draw(batch, parentAlpha);
		ArrayList<Skill> skills = player.getCastSkills();
		float y = this.y + 5;
		float x = this.x + CellSize - IconSize;
		
		for (Skill skill: skills)
		{
			if (skill.getLevel() <= 0) continue;
			if (skill.isPassive()) continue;
			drawSkill(skill, x, y, batch);
			x += CellSize;
		}
		
		width = Math.max(200, x - this.x);
		
		x = this.x + CellSize - IconSize;
		batch.end();
		Gdx.gl.glEnable(GL10.GL_BLEND);
		Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		shaper.begin(ShapeType.FilledRectangle);
		shaper.setColor(0.2f, 0.2f, 0.2f, 0.5f);
		for (Skill skill: skills)
		{
			if (skill.getLevel() <= 0) continue;
			if (skill.isPassive()) continue;
			drawColdownMask(skill, x, y, shaper);
			x += CellSize;
		}
		shaper.end();
		batch.begin();
	}

	
	@Override
	public boolean touchDown(float x, float y, int pointer) {
		float starty = 5;
		float startx = CellSize - IconSize;
		int index = 0;
		FuncBody: do 
		{
			if (y < starty || y > starty + IconSize)
				break FuncBody;
			
			ArrayList<Skill> skills = player.getCastSkills();
			index = (int) ((x - startx) / CellSize);
			if (index <= 0)
				break FuncBody;
			
			int skillsFound = 0;
			int lastSkill = -1;
			for (int i = 0; i < skills.size(); i++)
			{
				if (skills.get(i).isPassive()) continue;
				if (skills.get(i).getLevel() <= 0) continue;
				skillsFound++;
				if (skillsFound > index)
				{
					Skill s = skills.get(i);
					skills.set(i, skills.get(lastSkill));
					skills.set(lastSkill, s);
					break;
				}
				lastSkill = i;
			}
			

		} while (false);
		return super.touchDown(x, y, pointer);
	}
}
