package eu.eudat.elastic.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.elastic.criteria.Criteria;
import eu.eudat.elastic.entities.ElasticEntity;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by ikalyvas on 7/5/2018.
 */
public abstract class ElasticRepository<T extends ElasticEntity,C extends Criteria> implements Repository<T,C> {
    private static final Logger logger = LoggerFactory.getLogger(ElasticRepository.class);
    private RestHighLevelClient client;

    public RestHighLevelClient getClient() {
        return client;
    }

    public ElasticRepository(RestHighLevelClient client) {
        try {
            if (client.ping(RequestOptions.DEFAULT)) {
                this.client = client;
            }
        } catch (IOException e) {
            logger.warn("Unable to connect to Elastic Services");
            this.client = null;
        }
    }

    public  <T> T transformFromString(String value, Class<T> tClass) {
        ObjectMapper mapper = new ObjectMapper();
        T item = null;
        try {
            item = mapper.readValue(value, tClass);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return item;
    }
}
