/**
 * 
 */
package studio.junk.jam.coloritum;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;

import groovy.lang.Closure;

/**
 * Script base for asset mappers.
 * <p>
 * This script will map an asset name to an image path.
 * <p>
 * This class is used as base class for groovy scripts.
 * 
 * @author cryptjar
 */
public abstract class AssetScript extends NamedScript {

	Map<String, Object>	assetMapping	= new HashMap<String, Object>();
	TextureAtlas		atlas;

	protected class AssetSpec {
		public void image(String name, String path) {
			Array<AtlasRegion> arr = atlas.findRegions(path);

			assetMapping.put(name, arr.get(MathUtils.random(arr.size - 1)));
		}

		public void anim(String name, float frameTime, String path) {
			anim(name, frameTime, path, PlayMode.LOOP);
		}

		public void anim(String name, float frameTime, String path, PlayMode mode) {
			Animation anim = new Animation(frameTime, atlas.findRegions(path));
			anim.setPlayMode(mode);
			assetMapping.put(name, anim);
		}
	}

	public void load() {
		if (assetMapping != null) {
			System.err.println("Script " + scriptName + " was callen twice.");
		}

		assetMapping = new HashMap<String, Object>();

		run();
	}

	protected void atlas(String path) {
		if (atlas != null) {
			System.err.println("Script " + scriptName + " as Asset redefines atlas.");
		}

		atlas = new TextureAtlas(Gdx.files.internal(path));
	}

	protected void asset(Closure<?> cl) {
		if (atlas == null) {
			System.err.println("Script " + scriptName + " as Asset needs set atlas prior to define an asset.");
		}

		AssetSpec asset = new AssetSpec();
		Closure<?> code = cl.rehydrate(asset, this, this);
		code.setResolveStrategy(Closure.DELEGATE_ONLY);
		code.call();
	}

	public Map<String, Object> getMapping() {
		if (assetMapping == null) {
			System.err.println("Asset script not callen!");
			Thread.dumpStack();

			run();

			if (assetMapping == null) {
				System.err.println("Script: " + scriptName + " as Asset doesn't set a mapping!");
				return new HashMap<String, Object>();
			}
		}

		return assetMapping;
	}

}
