package p.studio.projectstate;

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

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

public class ProjectLocalStudioStateService {
    private static final ObjectMapper MAPPER = new ObjectMapper()
            .enable(SerializationFeature.INDENT_OUTPUT);

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

        try {
            final ProjectLocalStudioState loaded = MAPPER.readValue(statePath.toFile(), ProjectLocalStudioState.class);
            if (loaded == null || loaded.version() != ProjectLocalStudioState.CURRENT_VERSION) {
                return ProjectLocalStudioState.defaults();
            }
            return loaded;
        } catch (IOException | RuntimeException ignored) {
            return ProjectLocalStudioState.defaults();
        }
    }

    public void save(final ProjectReference projectReference, final ProjectLocalStudioState state) {
        final Path statePath = ProjectStudioPaths.statePath(projectReference);
        final ProjectLocalStudioState normalized = Objects.requireNonNull(state, "state");
        try {
            Files.createDirectories(statePath.getParent());
            MAPPER.writeValue(statePath.toFile(), normalized);
        } catch (IOException ioException) {
            throw new UncheckedIOException(ioException);
        }
    }
}
