package io.senslog.database;

import io.senslog.database.repository.AbstractRepository;
import io.senslog.database.repository.ObservationRepository;
import io.senslog.database.repository.SensorRepository;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DBRepositoryPool {

    private static final Map<Class<? extends AbstractRepository>, AbstractRepository> REPOSITORIES;

    static {
        REPOSITORIES = new HashMap<>();
    }

    public static void create(DBConfig config) throws IOException {
        DBConnection connection = new DBConnection();
        connection.connect(config);

        if (!connection.isConnected()) {
            throw new IOException("Can not connect to the database.");
        }


        REPOSITORIES.put(ObservationRepository.class, new ObservationRepository(connection));
        REPOSITORIES.put(SensorRepository.class, new SensorRepository(connection));
    }

    @SuppressWarnings("unchecked")
    public static <T> T getRepository(Class<T> tClass) throws IOException {
        if (REPOSITORIES.containsKey(tClass)) {
            return (T) REPOSITORIES.get(tClass);
        } else {
            throw new IOException("Repository class "+tClass+" is not registered.");
        }
    }
}
