package eu.dnetlib.index;

import java.lang.reflect.Type;
import java.net.URI;
import java.util.Map;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import eu.dnetlib.rmi.provision.IndexServiceException;
import org.springframework.beans.factory.annotation.Required;

public abstract class AbstractBackendDescriptor implements IndexServerDAO {

	protected Type typeToken = new TypeToken<Map<String, String>>() {
	}.getType();

	private Map<String, String> serviceProperties;

	private String jsonConfiguration;

	public void init() throws IndexServiceException {
		try {
			serviceProperties = new Gson().fromJson(getJsonConfiguration(), typeToken);
		} catch (Throwable e) {
			throw new IndexServiceException("unable to parse configuration: " + jsonConfiguration, e);
		}
	}

	public String getJsonConfiguration() {
		return jsonConfiguration;
	}

	@Required
	public void setJsonConfiguration(final String jsonConfiguration) {
		this.jsonConfiguration = jsonConfiguration;
	}

	protected URI getEndpointURL() {
		return URI.create(getEndpoint().get(ADDRESS));
	}

	@Override
	public Map<String, String> getServiceProperties() {
		return serviceProperties;
	}

	@Override
	public String getBackendId() {
		return getServiceProperties().get(ID);
	}

	@Override
	public Map<String, String> getEndpoint() {
		return Maps.filterKeys(getServiceProperties(), key -> key.equals(ID) || key.equals(ADDRESS));
	}

}
