using UnityEditor;
using UnityEngine;

public static class ScriptableObjectsCreator
{
    public static T CreateAsset<T>(string path, string name, bool unique) where T : ScriptableObject
    {
        T asset = ScriptableObject.CreateInstance<T>();

        //string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        //if (path == "")
        //{
        //    path = "Assets";
        //}
        //else if (Path.GetExtension(path) != "")
        //{
        //    path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
        //}

        var assetPathAndName = path + name + ".asset";
        if (unique)
            assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(assetPathAndName);

        CreateOrReplaceAsset(asset, assetPathAndName);
        //AssetDatabase.CreateAsset(asset, assetPathAndName);

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        //EditorUtility.FocusProjectWindow();
        //Selection.activeObject = asset;

        return AssetDatabase.LoadAssetAtPath<T>(assetPathAndName);
    }

    public static T CreateOrReplaceAsset<T>(T asset, string path) where T : Object
    {
        T existingAsset = AssetDatabase.LoadAssetAtPath<T>(path);

        if (existingAsset == null)
        {
            AssetDatabase.CreateAsset(asset, path);
            existingAsset = asset;
        }
        else
        {
            EditorUtility.CopySerialized(asset, existingAsset);
        }

        return existingAsset;
    }
}