package com.tandbergtv.watchpoint.pmm.assetlist;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import com.tandbergtv.cms.portal.util.transaction.Transactional;
import com.tandbergtv.watchpoint.pmm.dao.hibernate.HibernateContext;
import com.tandbergtv.watchpoint.pmm.entities.IAssetList;
import com.tandbergtv.watchpoint.search.QueryBuilder;
import com.tandbergtv.workflow.util.SearchCriteria;

public class AssetListSearchService<L extends IAssetList> implements IAssetListSearchService<L> {

	private Logger logger = Logger.getLogger(this.getClass());
	private String serviceName;
	
	public AssetListSearchService(String serviceName) {
		this.serviceName = serviceName;
	}
	
	@Override
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tandbergtv.watchpoint.pmm.schedule.search.IScheduleSearchService#
	 * count(com.tandbergtv.workflow.util.SearchCriteria)
	 */
	@Transactional
	public int count(SearchCriteria criteria) {
		String s = QueryBuilder.newInstance().buildCountQuery(criteria);
		logger.debug("Executing query :" + System.getProperty("line.separator") + s);
		
		Session session = getSession();
		Query query = session.createQuery(s);

		long count = (Long) query.uniqueResult();
		return (int)count;
	}
	
	@Override
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tandbergtv.watchpoint.pmm.schedule.search.IScheduleSearchService#
	 * search(com.tandbergtv.workflow.util.SearchCriteria)
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public Collection<L> search(SearchCriteria criteria) {
		String s = getQuery(criteria);
		
		logger.debug("Executing query :" + System.getProperty("line.separator") + s);
		
		Session session = getSession();
		Query query = session.createQuery(s);
		
		query.setFirstResult(criteria.getStartingRecordNumber());
		query.setMaxResults(criteria.getRecordsCount() == 0 ? Integer.MAX_VALUE 
				: criteria.getRecordsCount());

		return (Collection<L>) query.list();
	}
	
	/**
	 * Returns the select HQL query for the specified criteria
	 * 
	 * @param criteria
	 * @return
	 */
	public String getQuery(SearchCriteria criteria) {
		return QueryBuilder.newInstance().buildQuery(criteria);
	}
	
	@Override
	public String getServiceName() {
		return serviceName;	
	}

	@Override
	public void start() { }

	@Override
	public void stop() { }

	protected Session getSession() {
		return HibernateContext.getContext().getCurrentSession();
	}

}
