using UnityEngine;
using UnityEditor;
using System.Collections;

public class SeparateRGBA  {

	[MenuItem ("Window/Separate RGBA")]
	public static void Separate()
	{
		var texture = Selection.activeObject as Texture2D;
		if(texture == null)
		{
			return;
		}

		var path = AssetDatabase.GetAssetPath(texture);
		var importer = TextureImporter.GetAtPath(path) as TextureImporter;

		var wasReadable = importer.isReadable;
		if(!importer.isReadable)
		{
			importer.isReadable = true;
			AssetDatabase.ImportAsset(path);
		}

		var rgbPixels = texture.GetPixels();
		for(int i=0; i<rgbPixels.Length; i++)
		{
			rgbPixels[i].a = 1f;
		}

		CreateTextureFromPixels(rgbPixels, texture, "_rgb.png");

		var alphaPixels = texture.GetPixels();
		for(int i=0; i<alphaPixels.Length; i++)
		{
			alphaPixels[i].r = 0f;
			alphaPixels[i].g = 0f;
			alphaPixels[i].b = 0f;
		}

		CreateTextureFromPixels(alphaPixels, texture, "_alpha.png");

		AssetDatabase.Refresh();

		if(!wasReadable)
		{
			importer.isReadable = wasReadable;
			AssetDatabase.ImportAsset(path);
		}
	}

	static void CreateTextureFromPixels(Color[] pixels, Texture2D texture, string suffix)
	{
		var newTexture = new Texture2D(texture.width, texture.height, TextureFormat.ARGB32, false);
		newTexture.SetPixels(pixels);
		newTexture.Apply();

		var pngBytes = newTexture.EncodeToPNG();

		System.IO.File.WriteAllBytes(Application.dataPath + "/" + texture.name + suffix, pngBytes);
	}
}
