/*
Storybook: Open Source software for novelists and authors.
Copyright (C) 2008 - 2012 Martin Mustun

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package storybook.model.hbn.dao;

import com.googlecode.genericdao.dao.hibernate.GenericDAO;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NonUniqueResultException;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import storybook.model.hbn.entity.AbstractEntity;
import storybook.model.hbn.entity.Chapter;
import storybook.model.hbn.entity.Part;
import storybook.model.hbn.entity.Scene;
import storybook.tools.LOG;
import storybook.ui.dialog.ExceptionDlg;

public class ChapterDAO extends _GenericDAO<Chapter, Long>
		implements ChapterDAOInterface {

	public ChapterDAO() {
		super();
	}

	public ChapterDAO(Session session) {
		super(session);
	}

	public Chapter findFirst() {
		List<Chapter> ret = findAll();
		if (ret.isEmpty()) {
			return (null);
		}
		return ret.get(0);
	}

	@Override
	public List<Chapter> findAll() {
		return findAll(null);
	}

	@SuppressWarnings("unchecked")
	public List<Chapter> findAll(Part part) {
		StringBuilder buf = new StringBuilder("from Chapter");
		if (part != null) {
			buf.append(" where part=:part");
		}
		buf.append(" order by chapterno");
		Query query = session.createQuery(buf.toString());
		if (part != null) {
			query.setEntity(DAOutil.PART, part);
		}
		return (List<Chapter>) query.list();
	}

	public List<Chapter> findAllOrderByChapterNoAndSceneNo() {
		return findAllOrderByChapterNoAndSceneNo(null);
	}

	@SuppressWarnings("unchecked")
	public List<Chapter> findAllOrderByChapterNoAndSceneNo(Part part) {
		Criteria crit = session.createCriteria(Chapter.class);
		if (part != null) {
			crit.add(Restrictions.eq(DAOutil.PART, part));
		} else {
			crit.addOrder(Order.asc(DAOutil.PART));
		}
		crit.addOrder(Order.asc(DAOutil.CHAPTERNO));
		return crit.list();
	}

	public List<Scene> findUnassignedScenes() {
		return findScenes(null);
	}

	public Scene findFirstScene(Chapter chapter) {
		List<Scene> scenes = findScenes(chapter);
		if (scenes == null || scenes.isEmpty()) {
			return null;
		}
		return scenes.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Scene> findScenes(Chapter chapter) {
		List<Scene> scenes = new ArrayList<>();
		if (session.isOpen()) {
			Criteria crit = session.createCriteria(Scene.class);
			if (chapter != null) {
				crit.add(Restrictions.eq(DAOutil.CHAPTER, chapter));
			} else {
				crit.add(Restrictions.isNull(DAOutil.CHAPTER));
			}
			crit.addOrder(Order.asc(DAOutil.SCENE_NO));
			scenes = (List<Scene>) crit.list();
		}
		return scenes;
	}

	@SuppressWarnings("unchecked")
	public List<Scene> findScenesOrderByTimestamp(Chapter chapter) {
		List<Scene> scenes = new ArrayList<>();
		if (session.isOpen()) {
			Criteria crit = session.createCriteria(Scene.class);
			if (chapter != null) {
				crit.add(Restrictions.eq(DAOutil.CHAPTER, chapter));
			} else {
				crit.add(Restrictions.isNull(DAOutil.CHAPTER));
			}
			crit.addOrder(Order.asc("scenets"));
			scenes = (List<Scene>) crit.list();
		}
		return scenes;
	}

	public int getNextChapterNumber() {
		return getMaxChapterNumber() + 1;
	}

	public int getMaxChapterNumber() {
		Query query = session.createQuery("select max(chapterno) from Chapter");
		if (query.uniqueResult() == null) {
			return 0;
		}
		Integer ret = (Integer) query.uniqueResult();
		return ret;
	}

	@SuppressWarnings("unchecked")
	public boolean checkIfNumberExists(AbstractEntity entity) {
		try {
			Chapter newChapter = (Chapter) entity;
			Integer newChapterNo = newChapter.getChapterno();

			if (!entity.isTransient()) {
				// update
				ChapterDAO dao = new ChapterDAO(session);
				Chapter oldChapter = dao.find(entity.getId());
				Integer oldChapterNo = oldChapter.getChapterno();
				Criteria crit = session.createCriteria(Chapter.class);
				crit.add(Restrictions.eq(DAOutil.CHAPTERNO, newChapterNo));
				List<Chapter> chapters = (List<Chapter>) crit.list();
				List<Integer> numbers = new ArrayList<>();
				for (Chapter chapter : chapters) {
					numbers.add(chapter.getChapterno());
				}
				if (newChapterNo.equals(oldChapterNo)) {
					numbers.remove(newChapterNo);
				}
				return numbers.isEmpty();
			}

			// new
			Criteria crit = session.createCriteria(Chapter.class);
			crit.add(Restrictions.eq(DAOutil.CHAPTERNO, newChapterNo));
			List<Chapter> chapters = (List<Chapter>) crit.list();
			return chapters.size() <= 0;
		} catch (NonUniqueResultException e) {
			ExceptionDlg.show(this.getClass().getSimpleName()
					+ ".checkIfNumberExists(entity=" + LOG.trace(entity)
					+ ") NonUniqueResultException", e);
			return true;
		}
	}

	public Chapter findTitle(String str) {
		String nstr = str.trim();
		List<Chapter> list = findAll();
		for (Chapter p : list) {
			if (p.getName().trim().equals(nstr)) {
				return (p);
			}
		}
		return (null);
	}

}

interface ChapterDAOInterface extends GenericDAO<Chapter, Long> {
}
