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

public static class NormalConvert
{
    [MenuItem("Assets/Fix Normal", false, 1)]
    public static void ConvertNormal()
    {
        List<string> normalList = new List<string>();
        List<string> fullList = new List<string>();
        for (int i = 0; i < Selection.objects.Length; i++)
        {
            var texture = Selection.objects[i] as Texture2D;
            if (texture)
            {
                var assetPath = AssetDatabase.GetAssetPath(texture);
                var textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                if (textureImporter)
                {
                    fullList.Add(assetPath);
                    if (textureImporter.normalmap)
                        normalList.Add(assetPath);
                }
            }
        }

        if (fullList.Count > 0)
        {
            if (fullList.Count == normalList.Count)
                Convert(fullList);
            else
                NormalConvertWarning.OpenWindow(normalList, fullList, Convert);
        }
    }

    private static void Convert(List<string> pathList)
    {
        for (var i = 0; i < pathList.Count; i++)
            ConvertOneNormal(pathList[i]);
        AssetDatabase.Refresh(ImportAssetOptions.Default);
    }

    private static string GetFilePath(string assetPath)
    {
        return Application.dataPath + assetPath.Substring("Assets".Length);
    }

    public static void ConvertOneNormal(string path)
    {
        var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
        if (textureImporter == null)
            Debug.LogError(string.Format("无法找到图片:{0}", path));
        else if (textureImporter.textureType == TextureImporterType.NormalMap)
        {
            var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            textureImporter.isReadable = true;
            textureImporter.textureType = TextureImporterType.Default;
            textureImporter.crunchedCompression = false;
            textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
            textureImporter.SaveAndReimport();
            var colors = texture.GetPixels();
            for (int j = 0; j < colors.Length; j++)
            {
                var color = new Vector3(colors[j].r, colors[j].g, colors[j].b);
                color = color * 2f - Vector3.one;
                color.z = Mathf.Sqrt(1f - Mathf.Clamp01(color.x * color.x + color.y * color.y));
                color = color.normalized;
                color = (color + Vector3.one) * 0.5f;
                colors[j] = new Color(color.x, color.y, color.z, 1f);
            }

            string sourceFile = GetFilePath(path);
            //string sourceMeta = sourceFile + ".meta";
            var targetFile = sourceFile;
            if (Path.HasExtension(targetFile))
                targetFile = targetFile.Remove(targetFile.LastIndexOf('.'));
            targetFile = targetFile + ".png";
            //string targetMeta = targetFile + ".meta";
            Texture2D temp = new Texture2D(texture.width, texture.height, TextureFormat.ARGB32, false);
            temp.SetPixels(colors);
            //string sourceFileBackup = sourceFile + ".tbackup";
            // 只保存最早的备份文件,防止两次转换导致原始贴图丢失
            //if (File.Exists(sourceFileBackup))
            //    File.Delete(sourceFile);
            //else
            //    File.Move(sourceFile, sourceFileBackup);
            File.Delete(sourceFile);
            //if (sourceMeta != targetMeta)
            //    File.Move(sourceMeta, targetMeta);
            if (File.Exists(targetFile))
                File.Delete(targetFile);
            File.WriteAllBytes(targetFile, temp.EncodeToPNG());
            textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
            if (textureImporter != null)
            {
                textureImporter.textureType = TextureImporterType.NormalMap;
                textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
                textureImporter.mipmapEnabled = false;
                textureImporter.isReadable = false;
                textureImporter.SaveAndReimport();
                Debug.Log(string.Format("转换 {0} 为 {1}!", sourceFile, targetFile));
            }
        }
    }
}