using System.IO;
using UnityEditor;
using UnityEngine;

namespace BundleV2
{
    public class RemoveAssetWindow : EditorWindow
    {
        private Object _asset;

        private void OnGUI()
        {
            _asset = EditorGUILayout.ObjectField("To Remove", _asset, typeof(Object), false);
            GUILayout.Space(5f);
            if (GUILayout.Button("Remove") && _asset)
            {
                var asset = _asset;
                _asset = null;
                var assetPath = AssetDatabase.GetAssetPath(asset);
                if (!string.IsNullOrEmpty(assetPath) && assetPath.StartsWith(AssetConst.nonInternalHeader))
                {
                    var relativePath = assetPath.Substring(AssetConst.nonInternalHeader.Length);
                    var source = EditorCommonUtility.AssetToFilePath(assetPath);
                    var target = Application.dataPath.MoveUp().Open("UnusedAssets").Open(relativePath);
                    var dir = Path.GetDirectoryName(target);
                    if (!Directory.Exists(dir))
                        Directory.CreateDirectory(dir);
                    File.Move(source, target);
                    source += AssetConst.metaExtension;
                    if (File.Exists(source))
                    {
                        target += AssetConst.metaExtension;
                        File.Move(source, target);
                    }
                }
            }
        }

        [MenuItem("Bundle V2/Remove Asset")]
        public static void Create()
        {
            GetWindow<RemoveAssetWindow>();
        }
    }
}