package io.senslog.manager;

import io.senslog.database.DBException;
import io.senslog.database.DBRepositoryPool;
import io.senslog.database.repository.ObservationRepository;
import io.senslog.database.repository.SensorRepository;
import cz.hsrs.db.model.Observation;

import java.io.IOException;

import static cz.hsrs.track.TrackIgnitionSolver.IGNITION_SENSOR_ID;

public class ObservationManager {

    private final ObservationRepository observationRep;
    private final SensorRepository unitRep;

    public static ObservationManager newInstance() {
        try {
            ObservationRepository obsRep = DBRepositoryPool.getRepository(ObservationRepository.class);
            SensorRepository seRep = DBRepositoryPool.getRepository(SensorRepository.class);
            return new ObservationManager(obsRep, seRep);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public ObservationManager(ObservationRepository observationRep, SensorRepository unitRep) {
        this.observationRep = observationRep;
        this.unitRep = unitRep;
    }

    public void save(Observation observation) {

        if (observation.getSensorId() == IGNITION_SENSOR_ID) {
            // TODO solve
        }

        try {
            long obsId = observationRep.insert(observation);
            if (obsId <= 0) {
                throw new RuntimeException("Observation was not inserted successfully.");
            }
        } catch (DBException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

}
