﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;




#if NGUI_Exists 
public class ExportAllSprite
{
	[MenuItem("CHP/Export sprites", false, -1)]

	static void ExportSprite(){
		var sels = Selection.GetFiltered(typeof(GameObject), SelectionMode.Assets);

		List< UIAtlas> allAtlas = new List<UIAtlas>();

		foreach (GameObject obj in sels){
			Debug.Log( obj.name);
			UIAtlas atlas = obj.GetComponent<UIAtlas>();
			if (atlas != null){
				if (! allAtlas.Contains(atlas)){
					allAtlas.Add( atlas);
				}
			}
		}

		foreach( UIAtlas atlas in allAtlas){
			Debug.Log(atlas.name);
			string path = System.IO.Directory.GetParent(Application.dataPath).ToString() + "\\ExportedSprites";
			
			

			foreach (UISpriteData sd in atlas.spriteList){
				if (!string.IsNullOrEmpty(path))
				{
					
					string currentPath = System.IO.Path.Combine(path, atlas.name);
					if (!System.IO.Directory.Exists(currentPath))
					{
						System.IO.Directory.CreateDirectory(currentPath);
					}

					UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(atlas, sd.name);

					if (se != null)
					{
						byte[] bytes = se.tex.EncodeToPNG();
						string fileName = System.IO.Path.Combine(currentPath, (sd.name + ".png"));
						System.IO.File.WriteAllBytes(fileName, bytes);
						Debug.Log("export: " + fileName);
					}
				}	
			}
		}
	}

}

#endif