package p.studio.projectstate;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.projects.ProjectReference;
import p.studio.projects.ProjectStudioPaths;

import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.assertEquals;

final class ProjectLocalStudioSetupServiceTest {
    @TempDir
    Path tempDir;

    @Test
    void loadsDedicatedProjectSetupFile() throws Exception {
        final ProjectLocalStudioSetupService service = new ProjectLocalStudioSetupService();
        final ProjectReference project = project("main");
        Files.createDirectories(ProjectStudioPaths.studioRoot(project));
        Files.writeString(
                ProjectStudioPaths.setupPath(project),
                """
                {
                  "prometeuRuntimePath": "/opt/prometeu/runtime",
                  "editorIndentation": {
                    "mode": "spaces",
                    "width": 2
                  }
                }
                """);

        assertEquals(
                new ProjectLocalStudioSetup(
                        "/opt/prometeu/runtime",
                        new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", 2)),
                service.load(project));
    }

    @Test
    void missingDedicatedProjectSetupFileFallsBackToDefaults() {
        final ProjectLocalStudioSetupService service = new ProjectLocalStudioSetupService();

        assertEquals(ProjectLocalStudioSetup.defaults(), service.load(project("main")));
    }

    @Test
    void malformedDedicatedProjectSetupFileFallsBackToDefaults() throws Exception {
        final ProjectLocalStudioSetupService service = new ProjectLocalStudioSetupService();
        final ProjectReference project = project("main");
        Files.createDirectories(ProjectStudioPaths.studioRoot(project));
        Files.writeString(ProjectStudioPaths.setupPath(project), "{ not valid json");

        assertEquals(ProjectLocalStudioSetup.defaults(), service.load(project));
    }

    @Test
    void saveWritesNormalizedDedicatedProjectSetupFile() throws Exception {
        final ProjectLocalStudioSetupService service = new ProjectLocalStudioSetupService();
        final ProjectReference project = project("main");

        service.save(
                project,
                new ProjectLocalStudioSetup(
                        " /opt/prometeu/runtime ",
                        new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", 8)));

        assertEquals(
                new ProjectLocalStudioSetup(
                        "/opt/prometeu/runtime",
                        new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", 8)),
                service.load(project));
    }

    private ProjectReference project(final String name) {
        final Path projectRoot = tempDir.resolve(name);
        return new ProjectReference("Main", "1.0.0", "pbs", 1, projectRoot);
    }
}
