package p.studio.projectstate;

import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.projects.ProjectReference;
import p.studio.projects.ProjectStudioPaths;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

public class ProjectLocalStudioSetupService {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public ProjectLocalStudioSetup load(final ProjectReference projectReference) {
        final Path setupPath = ProjectStudioPaths.setupPath(projectReference);
        if (!Files.isRegularFile(setupPath)) {
            return ProjectLocalStudioSetup.defaults();
        }

        try {
            final ProjectLocalStudioSetup loaded = MAPPER.readValue(setupPath.toFile(), ProjectLocalStudioSetup.class);
            return loaded == null ? ProjectLocalStudioSetup.defaults() : loaded;
        } catch (IOException | RuntimeException ignored) {
            return ProjectLocalStudioSetup.defaults();
        }
    }

    public void save(final ProjectReference projectReference, final ProjectLocalStudioSetup setup) {
        final Path setupPath = ProjectStudioPaths.setupPath(projectReference);
        final ProjectLocalStudioSetup normalized = Objects.requireNonNull(setup, "setup");
        try {
            Files.createDirectories(setupPath.getParent());
            MAPPER.writerWithDefaultPrettyPrinter().writeValue(setupPath.toFile(), normalized);
        } catch (IOException ioException) {
            throw new RuntimeException("unable to save project setup: " + setupPath, ioException);
        }
    }
}
