package com.qiankun.dao;

import java.util.Date;
import java.util.List;

import com.google.common.base.Strings;
import org.springframework.stereotype.Repository;

import com.qiankun.dao.core.AbsDao;
import com.qiankun.dao.core.Hints;
import com.qiankun.entity.Activity;
import com.qiankun.pages.IPageList;
import com.qiankun.pages.PageListImpl;

@Repository
public class ActivityDaoImpl extends AbsDao<Activity, String> implements ActivityDao {
	
	
	private static final String FIND_ACTIVITY_PAGE = " from Activity where name like ?  ";
	
	private static final String FIND_ACTIVITY_BY_TYPE = " from Activity where type = ?  ";
	
	
	@Override
	public IPageList<Activity> findActivityPage(String searchStr, String type, String order, String sort, Hints hints) {
		
		
		if (order == null){
			order = " createTime ";
		}
		if (sort == null){
			sort=" desc ";
		}
		
		String hql = "";
		if (type != null){
			hql = " and type = '" + type + "'";
		}
		
		if (searchStr == null) {
			searchStr = "%";
		}
		String param = "%" + searchStr + "%";
		IPageList<Activity> activitys = new PageListImpl<Activity>();
		
		activitys.setRecords(find(FIND_ACTIVITY_PAGE + hql + sortHQL(order, sort), hints, param));
		activitys.setRecordTotal(findCount(" select count(*) " + FIND_ACTIVITY_PAGE + hql, param));
		
		
		return activitys;
	}

    @Override
    public List<Activity> findByAvailableAndType(Boolean available,String type) {

    	String hql = "";
    	if (available != null) {
    		hql += " and available = " + available;
    	}
    	hql += " order by createTime desc ";
    		
        return find(FIND_ACTIVITY_BY_TYPE + hql, new Hints(), type);
    }

    @Override
    public IPageList<Activity> findPageList(String userId, Hints hints) {
	    String hsql = "";
        IPageList<Activity> activitys = new PageListImpl<Activity>();
	    if(Strings.isNullOrEmpty(userId)){
            hsql = " from Activity order by available desc,createTime desc";
            activitys.setRecords(find(hsql, hints));
            activitys.setRecordTotal(findCount(" select count(*) " + hsql));
        }else {
	        hsql = " from Activity a inner join a.activityReg r where r.user.id = ? order by a.createTime desc";
            activitys.setRecords(find("select a " + hsql, hints,userId));
            activitys.setRecordTotal(findCount(" select count(*) " + hsql, userId));
        }
        return activitys;
    }
}
