using Ghost.Editor.Core;
using Ghost.Editor.Core.Services;
using Ghost.Editor.Core.Utilities;
using Ghost.Editor.Views.Controls;
using Ghost.Engine.Core;

namespace Ghost.Editor.ContextMenu;

internal static class ContentBrowserContextMenu
{
    [ContextMenuItem("project-browser", "Show in Explorer")]
    private static void ShowInExplorer()
    {
        var path = ContentBrowser.LastFocused?.ViewModel.CurrentDirectoryPath;
        if (!Directory.Exists(path))
        {
            return;
        }

        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
        {
            FileName = path,
            UseShellExecute = true,
            Verb = "open"
        });
    }

    [ContextMenuItem("project-browser", "Create/Folder")]
    private static void CreateFolder()
    {
        // TODO: Use AssetService

        var viewModel = ContentBrowser.LastFocused?.ViewModel;
        if (viewModel is null)
        {
            return;
        }

        var currentDir = viewModel.CurrentDirectoryPath;
        if (!Directory.Exists(currentDir))
        {
            return;
        }

        var newFolderPath = Path.Combine(currentDir, "New Folder");
        var folderIndex = 1;
        while (Directory.Exists(newFolderPath))
        {
            newFolderPath = Path.Combine(currentDir, $"New Folder ({folderIndex})");
            folderIndex++;
        }

        Directory.CreateDirectory(newFolderPath);
        // Refresh the view model to show the new folder
        viewModel.NavigateToDirectory(currentDir);
    }

    [ContextMenuItem("project-browser", "Create/Asset/Scene")]
    private static void CreateSceneAsset()
    {
        var viewModel = ContentBrowser.LastFocused?.ViewModel;
        if (viewModel is null)
        {
            return;
        }

        var currentDir = viewModel.CurrentDirectoryPath;
        if (!Directory.Exists(currentDir))
        {
            return;
        }

        var newScenePath = PathUtility.GetUniqueName(Path.Combine(currentDir, "New Scene.gscene"));
        var tempScene = SceneManager.CreateScene();

        var sceneSerializationService = App.GetService<SceneSerializationService>();
        sceneSerializationService.SaveSceneFromEditorWorld(newScenePath, tempScene);

        SceneManager.DestroyScene(tempScene, App.GetService<IEditorWorldService>().EditorWorld);
    }
}
