package com.lerx.dao.impl;

import java.util.List;

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

import com.lerx.dao.iface.IAlbgenreMangerDao;
import com.lerx.entities.Albgenre;
import com.lerx.entities.AlbgenreManger;

public class AlbgenreMangerDaoImpl extends HibernateDaoSupport implements IAlbgenreMangerDao {

	@Override
	public AlbgenreManger add(AlbgenreManger manger) {
		this.getHibernateTemplate().save(manger);
		Albgenre albgenre=manger.getAlbgenre();
		albgenre.setMangers(staByAlbgenrID(albgenre.getId()));
		this.getHibernateTemplate().update(albgenre);
		return manger;
	}

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

	@Override
	public boolean delByID(long id) {
		AlbgenreManger manger=findByID(id);
		if (manger==null) {
			return false;
		}
		Albgenre albgenre=manger.getAlbgenre();
		this.getHibernateTemplate().delete(findByID(id));

		if (findByID(id) == null) {
			
			albgenre.setMangers(staByAlbgenrID(albgenre.getId()));
			this.getHibernateTemplate().update(albgenre);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public List<AlbgenreManger> queryByAlbgenrID(long aid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbgenreManger.class);
		criteria.createAlias("albgenre", "a"); 
		criteria.add(Restrictions.eq("a.id", aid ) );
		criteria.addOrder(Order.asc("id") );
		@SuppressWarnings("unchecked")
		List<AlbgenreManger> list=(List<AlbgenreManger>) this.getHibernateTemplate().findByCriteria(criteria);
		
		return list;
	}

	@Override
	public AlbgenreManger findByUID(long aid,long uid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbgenreManger.class);
		criteria.createAlias("albgenre", "a"); 
		criteria.add(Restrictions.eq("a.id", aid ) );
		criteria.createAlias("user", "u"); 
		criteria.add(Restrictions.eq("u.id", uid ) );
		criteria.addOrder( Order.asc("id") );
		
		@SuppressWarnings("unchecked")
		List<AlbgenreManger> list=(List<AlbgenreManger>) this.getHibernateTemplate().findByCriteria(criteria);
		if (!list.isEmpty() && list.size()>0) {
			return list.get(0);
		}
		return null;
		
	}

	@Override
	public int staByAlbgenrID(long aid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbgenreManger.class);
		criteria.createAlias("albgenre", "a"); 
		criteria.add(Restrictions.eq("a.id", aid ) );
		criteria.setProjection(Projections.rowCount());
		criteria.addOrder( Order.asc("id") );
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		int total=Integer.valueOf(String.valueOf(list.get(0)));
		return total;
	}

}
