package com.lerx.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.lerx.dao.iface.IVisitorCountInPeriodDao;
import com.lerx.entities.VisitorCountInPeriod;

public class VisitorCountInPeriodDaoImpl extends HibernateDaoSupport implements IVisitorCountInPeriodDao {

	@Override
	public VisitorCountInPeriod add(VisitorCountInPeriod vcip) {
		VisitorCountInPeriod vcipfind=findByPeriod(vcip.getVa().getId(),vcip.getHour());
		if (vcipfind==null) {
			this.getHibernateTemplate().save(vcip);
			return vcip;
		}else {
			return vcipfind;
		}
	}

	@Override
	public void modify(VisitorCountInPeriod vcip) {
		this.getHibernateTemplate().update(vcip);

	}

	@Override
	public VisitorCountInPeriod findByID(long id) {
		return this.getHibernateTemplate().get(VisitorCountInPeriod.class, id);
	}

	@Override
	public VisitorCountInPeriod findByPeriod(long vid, int hour) {
		
		DetachedCriteria criteria=DetachedCriteria.forClass(VisitorCountInPeriod.class);
		criteria.createAlias("va", "v"); 
		criteria.add(Restrictions.eq("v.id", vid ) );
		criteria.add(Restrictions.eq("hour", hour ) );
		
		@SuppressWarnings("unchecked")
		List<VisitorCountInPeriod> list = (List<VisitorCountInPeriod>) this.getHibernateTemplate().findByCriteria(criteria);
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public long count(long vid,int hour) {
		
		DetachedCriteria criteria=DetachedCriteria.forClass(VisitorCountInPeriod.class);
		criteria.setProjection(Projections.rowCount());
		criteria.createAlias("va", "v"); 
		criteria.add(Restrictions.eq("v.id", vid ) );
		criteria.add(Restrictions.eq("hour", hour ) );
		
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		if (list.size()>0) {
			return list.get(0);
		}
		return 0;
	}

	@Override
	public long sum(long vid,int hour,int mode) {
		
		DetachedCriteria criteria=DetachedCriteria.forClass(VisitorCountInPeriod.class);
		
		if (mode==0) {
			criteria.setProjection(Projections.sum("totalView"));
		}else {
			criteria.setProjection(Projections.sum("totalIP"));
		}
		criteria.add(Restrictions.eq("hour", hour ) );
		criteria.createAlias("va", "v"); 
		criteria.createAlias("v.vbook", "b"); 
		criteria.add(Restrictions.eq("b.id", vid ) );
		
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		long sum;
		if (list!=null && !list.isEmpty() && list.size()>0) {
			if (list.get(0)==null) {
				sum=0;
			}else {
				sum = list.get(0);
			}
			
		}else {
			sum=0;
		}
		
		return sum;
		
	}

}
