package click.kamil.springstatemachineexporter.service;

import click.kamil.springstatemachineexporter.analysis.model.AnalysisResult;
import click.kamil.springstatemachineexporter.model.StateMachineModel;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.nio.file.Path;

public class JsonImportService {

    private final ObjectMapper objectMapper;

    public JsonImportService() {
        this.objectMapper = new ObjectMapper();
    }

    public StateMachineModel importJson(Path jsonFile) throws IOException {
        StateMachineModel model = objectMapper.readValue(jsonFile.toFile(), StateMachineModel.class);
        if (model.getName() == null) {
            String fileName = jsonFile.getFileName().toString();
            int dot = fileName.lastIndexOf('.');
            model.setName(dot > 0 ? fileName.substring(0, dot) : fileName);
        }
        return model;
    }

    public AnalysisResult importAnalysisResult(Path jsonFile) throws IOException {
        return objectMapper.readValue(jsonFile.toFile(), AnalysisResult.class);
    }
}
