package eu.dnetlib.common.logging;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;

import eu.dnetlib.common.logging.conf.DnetLogConfigurationLoader;
import eu.dnetlib.common.logging.dao.DnetLoggerDao;

public class DnetLogger implements Iterable<Map<String, String>> {

	private String name;

	private Resource indexConf;

	@javax.annotation.Resource
	private DnetLoggerDao dao;

	@PostConstruct
	public void init() {
		dao.init(name);
		dao.configureIndex(name, DnetLogConfigurationLoader.getIndexedPaths(indexConf));
	}

	public LogMessage newLogMessage(final DnetLogLevel level) {
		return new LogMessage(dao, name, level);
	}

	public LogMessage newLogMessage() {
		return newLogMessage(DnetLogLevel.INFO);
	}

	public Iterator<Map<String, String>> find(final String key, final String value) {
		return dao.find(name, key, value);
	}

	public Iterator<Map<String, String>> find(final Map<String, Object> criteria) {
		return dao.find(name, criteria);
	}

	public Map<String, String> findOne(final String key, final String value) {
		return dao.findOne(name, key, value);
	}

	public Iterator<Map<String, String>> find(final String cql, final List<String> fields) {
		return dao.find(name, cql, fields);
	}

	@Override
	public Iterator<Map<String, String>> iterator() {
		return dao.obtainLogIterator(name);
	}

	public String getName() {
		return name;
	}

	@Required
	public void setName(final String name) {
		this.name = name;
	}

	public Resource getIndexConf() {
		return indexConf;
	}

	public void setIndexConf(final Resource indexConf) {
		this.indexConf = indexConf;
	}

	public Iterator<Map<String, String>> range(final Date startDate, final Date endDate) {
		return dao.findByDateRange(name, startDate, endDate);
	}

	public Iterator<Map<String, String>> range(final Date startDate, final Date endDate, final String key, final String value) {
		return dao.findByDateRange(name, startDate, endDate, key, value);
	}

	public Iterator<Map<String, String>> range(final Date startDate, final Date endDate, final Map<String, Object> criteria) {
		return dao.findByDateRange(name, startDate, endDate, criteria);
	}

}
