//--------------------------------------
//               PowerUI
//
//        For documentation or 
//    if you have any issues, visit
//        powerUI.kulestar.com
//
//    Copyright  2013 Kulestar Ltd
//          www.kulestar.com
//--------------------------------------

using UnityEditor;
using UnityEngine;
using System.Threading;
using System.IO;

namespace PowerUI{

	/// <summary>
	/// Handles automatically applying the required import settings to images.
	/// </summary>
	
	public static class ImageImport{
		
		/// <summary>Applies the required image import settings to the given image.</summary>
		/// <param name="imagePath">The image path (relative to the project) to apply the settings to.</param>
		public static void Apply(string imagePath){
			
			// Does it exist?
			if(Directory.Exists(imagePath)){
				// It's actually a directory.
				// Apply to everything inside it (and recurse too).
				ApplyToAll(imagePath);
				return;
			}
			
			if(!File.Exists(imagePath)){
				return;
			}
			
			// Grab the importer:
			TextureImporter importer=AssetImporter.GetAtPath(imagePath) as TextureImporter;
			
			if(importer==null){
				return;
			}
			
			#if !UNITY_5_5_OR_NEWER
			// Advanced:
			importer.textureType=TextureImporterType.Advanced;
			#endif
			
			// Non power of two:
			importer.npotScale=TextureImporterNPOTScale.None;
			// No mipmaps:
			importer.mipmapEnabled=false;
			// Make it readable:
			importer.isReadable=true;
			
			// Reimport (applies the settings):
			AssetDatabase.ImportAsset(imagePath,ImportAssetOptions.ForceUpdate); 
		}
		
		
		/// <summary>Applies to all images in the given directory.</summary>
		/// <param name="path">The path to apply settings to.</param.
		public static void ApplyToAll(string path){
			if(path==null){
				return;
			}
			
			string[] allImages=Directory.GetFiles(path);
			ApplyToAll(allImages);
			
			// Import sub-directories too:
			string[] allDirectories=Directory.GetDirectories(path);
			
			for(int i=0;i<allDirectories.Length;i++){
				ApplyToAll(allDirectories[i]);
			}
		}
		
		/// <summary>Applies to all of the given image paths.</summary>
		/// <param name="allImages">A set of all images to apply default settings to.</param>
		public static void ApplyToAll(string[] allImages){
			if(allImages==null){
				return;
			}
			
			Debug.Log("Importing "+allImages.Length+" images..");
			
			for(int i=0;i<allImages.Length;i++){
				Apply(allImages[i]);
			}
		}
		
	}

}