package ru.yandex.autotests.direct.utils.beans;

import ru.yandex.autotests.direct.utils.DirectUtilsException;
import ru.yandex.autotests.direct.utils.mongo.WrappedBeansMongoHelper;

import java.util.List;

public class MongoBeanLoader<T> {
    private final WrappedBeansMongoHelper<T> wrappedBeansMongoHelper;

    public MongoBeanLoader(Class<T> beanClass, String collectionName) {
        this.wrappedBeansMongoHelper = new WrappedBeansMongoHelper<>(beanClass, collectionName);
    }

    public MongoBeanLoader(WrappedBeansMongoHelper<T> wrappedBeansMongoHelper) {
        this.wrappedBeansMongoHelper = wrappedBeansMongoHelper;
    }

    public void saveBean(T bean, String templateName) {
        try{
            wrappedBeansMongoHelper.addMongoBean(templateName, bean);
        } catch (Exception e) {
            throw new PropertyLoaderException(e);
        }
    }

    public T getBean(String templateName) {
        try{
            T bean = wrappedBeansMongoHelper.getBean(templateName);
            if(bean == null) {
                throw new DirectUtilsException("Template '" + templateName +"' not found in mongo");
            }
            return bean;
        } catch (Exception e) {
            throw new DirectUtilsException("Exception while obtaining bean from mongo", e);
        }
    }

    public List<T> getBeans(String templateName) throws PropertyLoaderException {
        try{
            return wrappedBeansMongoHelper.getBeans(templateName);
        } catch (Exception e) {
            throw new DirectUtilsException("Exception while obtaining bean from mongo", e);
        }
    }

    public void removeBean(String templateName) {
        try{
            wrappedBeansMongoHelper.deleteMongoBean(templateName);
        } catch (Exception e) {
            throw new PropertyLoaderException(e);
        }
    }
}
