using System.Collections.Generic;
using Godot;

public class FileHandler
{
    private const string ScriptDirectory = "user://scripts";
    private const string ScriptExtension = ".dsl";

    public static void CreateScriptDirectory()
    {
        DirAccess.MakeDirRecursiveAbsolute(ScriptDirectory);
    }

    public static void SaveProgram(string filename, string content)
    {
        CreateScriptDirectory();
        string path = GetProgramPath(filename);

        FileAccess file = FileAccess.Open(path, FileAccess.ModeFlags.Write);
        file.StoreString(content);
    }

    public static List<string> LoadProgramNames()
    {
        CreateScriptDirectory();
        List<string> programs = new List<string>();

        DirAccess dir = DirAccess.Open(ScriptDirectory);
        if (dir == null)
        {
            return programs;
        }

        dir.ListDirBegin();
        while (true)
        {
            string fileName = dir.GetNext();
            if (fileName == "")
                break;

            if (!dir.CurrentIsDir() && fileName.EndsWith(ScriptExtension))
            {
                programs.Add(fileName.Replace(ScriptExtension, ""));
            }
        }
        dir.ListDirEnd();

        return programs;
    }

    public static string LoadProgram(string name)
    {
        CreateScriptDirectory();
        string path = GetProgramPath(name);

        if (!FileAccess.FileExists(path))
        {
            return "";
        }

        FileAccess file = FileAccess.Open(path, FileAccess.ModeFlags.Read);
        return file.GetAsText();
    }

    private static string GetProgramPath(string filename)
    {
        return $"{ScriptDirectory}/{filename}{ScriptExtension}";
    }
}
