using UnityEngine;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class TexturePacker {
	
	[System.Serializable]
	public class TextureAtlas
	{
		[XmlAttribute ("imagePath")]
		public string path;
		[XmlAttribute ("width")]
		public int width;
		[XmlAttribute ("height")]
		public int height;
		[XmlElement ("sprite")]
		public SpriteInAtlas[] sprite;
	}
	
	[System.Serializable]
	public class SpriteInAtlas
	{
		[XmlAttribute ("n")]
		public string name;
		[XmlAttribute ("x")]
		public int left;
		[XmlAttribute ("y")]
		public int top;
		[XmlAttribute ("w")]
		public int width;
		[XmlAttribute ("h")]
		public int height;
	}
	
	public class AtlasInfo{
		public Vector2 size;
		public Texture2D texture;
	}
	
	public class SpriteInfo{
		public string name;
		public Vector2 borders;
		public Rect textureCoords;
		public AtlasInfo atlas;
	}
	
	private SpriteInfo[] sprites;
	
	public SpriteInfo SpriteByName(string name){
		foreach(SpriteInfo sprite in sprites){
			if (sprite.name == name){
				return sprite;
			}
		}
		return null;
	}
	
	public TexturePacker(Texture2D texture, TextAsset description){
		sprites = Load(texture, description);
	}
	
	public TexturePacker(string textureFileName, string atlasFileName){
		sprites = Load(Resources.Load(textureFileName) as Texture2D, Resources.Load(atlasFileName) as TextAsset);
	}
	
	SpriteInfo[] Load(Texture2D texture, TextAsset asset){
		TextureAtlas atlas = new TextureAtlas();
		XmlSerializer serialReader = new XmlSerializer(typeof(TextureAtlas));
		SpriteInfo[] info = new SpriteInfo[0];
		if (asset != null){
			Stream writer = new MemoryStream(asset.bytes);	
			atlas = serialReader.Deserialize(writer) as TextureAtlas;	
			writer.Close();
			AtlasInfo atlasInfo = new AtlasInfo();
			atlasInfo.size = new Vector2(atlas.width, atlas.height);
			atlasInfo.texture = texture;
			info = new SpriteInfo[atlas.sprite.Length];
			for(int i = 0; i < atlas.sprite.Length; i++){
				info[i] = new SpriteInfo();
				info[i].name = atlas.sprite[i].name;
				info[i].textureCoords = new Rect(
					atlas.sprite[i].left / (float)atlas.width,
					1 - atlas.sprite[i].top  / (float)atlas.height - atlas.sprite[i].height / (float)atlas.height,
					atlas.sprite[i].width  / (float)atlas.width,
					atlas.sprite[i].height / (float)atlas.height
					);
				info[i].atlas = atlasInfo;
			}
		}
		else
			Debug.Log("File not found ");
		return info;
	}
	
}
