package com.lerx.dao.impl;

import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.lerx.dao.iface.IAlbumArticleHistoryDao;
import com.lerx.entities.AlbumArticle;
import com.lerx.entities.AlbumArticleContent;
import com.lerx.entities.AlbumArticleHistory;
import com.lerx.hql.entities.Rs;
import com.lerx.hql.util.HibernateCallbackUtil;
import com.lerx.hql.util.HibernateUtil;

public class AlbumArticleHistoryDaoImpl extends HibernateDaoSupport implements IAlbumArticleHistoryDao {

	@Override
	public AlbumArticleHistory add(AlbumArticleHistory history) {
		this.getHibernateTemplate().save(history);
		return history;
	}

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

	@Override
	public boolean delByID(long id) {
		this.getHibernateTemplate().delete(findByID(id));

		if (findByID(id) == null) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public void delAfterID(long id) {
		AlbumArticleHistory history=this.getHibernateTemplate().get(AlbumArticleHistory.class, id);
		if (history.getContent()!=null) {
			AlbumArticle art=history.getArt();
			long contentID=history.getContent().getId();
			AlbumArticleContent content=this.getHibernateTemplate().get(AlbumArticleContent.class, contentID);
			art.setContent(content);
			this.getHibernateTemplate().update(art);
			this.getHibernateTemplate().flush();
//			this.getHibernateTemplate().bulkUpdate(hql);
			String hql = "delete from AlbumArticleHistory a where a.id>" +id + " and a.art.id="+art.getId();
//			this.getHibernateTemplate().bulkUpdate(hql);
			HibernateUtil.executeHql(this.getHibernateTemplate(), hql);
			
			hql = "delete from AlbumArticleContent a where a.id>" + contentID
					+ " and a.art.id=" + history.getArt().getId();
			HibernateUtil.executeHql(this.getHibernateTemplate(), hql);
		}
	}
	
	@Override
	public Rs queryByArtID(long aid, int page, int pagesize) {
		String hql = "from AlbumArticleHistory a where a.art.id="+aid+" order by a.id desc";
		return HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, 0, page, pagesize);
	}

	@Override
	public Rs queryByAlbumID(long aid, int page, int pagesize) {
		String hql = "from AlbumArticleHistory a where a.art.album.id="+aid+" order by a.id desc";
		return HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, 0, page, pagesize);
	}

	@Override
	public void restoreToCurr(AlbumArticleHistory history) {
		// TODO Auto-generated method stub

	}

}
