package com.telephoners.krakyournet.ctf.repositories;

import org.mongodb.morphia.Datastore;

import javax.inject.Inject;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public abstract class Repository<T>
{
    protected Datastore datastore;

    @Inject
    public Repository(Datastore datastore)
    {
        this.datastore = datastore;
    }

    public void add(T item)
    {
        datastore.save(item);
    }

    public List<T> getAll()
    {
        //todo: unchecked cast
        return datastore.createQuery(getRepositoryType()).asList();
    }

    public void clean()
    {
        datastore.getCollection(getRepositoryType()).drop();
    }

    Class getRepositoryType()
    {
        try {
            return Class.forName((((ParameterizedType) this.getClass().getGenericSuperclass())
                    .getActualTypeArguments()[0]).getTypeName());
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Class not found");
        }
    }
}
