using UnityEngine;
using UnityEditor;
using System.IO;

[InitializeOnLoad]
public class EmptyFolderDestroyer {

    static EmptyFolderDestroyer(){
        EditorApplication.playModeStateChanged += state => {
            if(state == PlayModeStateChange.EnteredEditMode){
                DirectoryInfo directory = new DirectoryInfo(Application.dataPath);
                CheckFolder(directory);
            }
        };
    }

    private static bool CheckFolder(DirectoryInfo directory){
        DirectoryInfo[] childrens = directory.GetDirectories();
        if(childrens.Length > 0){
            bool deleted = false;
            foreach(DirectoryInfo childDirectory in childrens){
                deleted = CheckFolder(childDirectory);
            }
            return deleted ? CheckFolder(directory) : false;
        }else if(directory.GetFiles().Length <= 0){
            DeleteFolder(directory.FullName);
            return true;
        }else{
            return false;
        }
    }

    private static void DeleteFolder(string path){
        Debug.Log(string.Format("空フォルダを削除 : {0}", path));
        System.IO.Directory.Delete(path, true);
        System.IO.File.Delete(string.Format("{0}.meta", path));
    }
}
