/*
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.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
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.Projections;
import org.hibernate.criterion.Restrictions;
import storybook.model.hbn.entity.AbstractEntity;
import storybook.model.hbn.entity.Scene;
import storybook.model.hbn.entity.Strand;
import storybook.tools.LOG;
import storybook.ui.dialog.ExceptionDlg;

public class StrandDAO extends _GenericDAO<Strand, Long>
		implements StrandDAOInterface {

	public StrandDAO() {
		super();
	}

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

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

	public long countByDate(Date date, Strand strand) {
		Criteria crit = session.createCriteria(Scene.class);
		crit.add(Restrictions.eq("sceneTs", new Timestamp(date.getTime())));
		crit.add(Restrictions.eq(DAOutil.STRAND, strand));
		crit.setProjection(Projections.rowCount());
		return (Long) crit.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<Strand> findAllByName() {
		Criteria crit = session.createCriteria(Strand.class);
		crit.addOrder(Order.asc(DAOutil.NAME));
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public List<Strand> findAllOrderBySort() {
		Criteria crit = session.createCriteria(Strand.class);
		crit.addOrder(Order.asc(DAOutil.SORT));
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public List<String> findAllInList() {
		Query query = session.createQuery("from Strand"
				+ " order by name");
		List<String> list = new ArrayList<>();
		for (Strand s : (List<Strand>) query.list()) {
			list.add(s.getName());
		}
		return (list);
	}

	public void orderStrands() {
		int i = 0;
		for (Strand s : findAllOrderBySort()) {
			s.setSort(i);
			session.update(s);
			++i;
		}
	}

	public void orderUpStrand(Strand strand) {
		if (strand.getSort() == 0) {
			return;
		}
		session.refresh(strand);
		int strandSort = strand.getSort();
		Criteria crit = session.createCriteria(Strand.class);
		crit.add(Restrictions.eq(DAOutil.SORT, strand.getSort() - 1));
		Strand upper = (Strand) crit.uniqueResult();
		int upperSort = upper.getSort();
		strand.setSort(upperSort);
		upper.setSort(strandSort);
		session.update(strand);
		session.update(upper);
	}

	public void orderDownStrand(Strand strand) {
		session.refresh(strand);
		int strandSort = strand.getSort();
		Criteria crit = session.createCriteria(Strand.class);
		crit.add(Restrictions.eq(DAOutil.SORT, strand.getSort() + 1));
		Strand lower = (Strand) crit.uniqueResult();
		if (lower == null) {
			return;
		}
		int lowerSort = lower.getSort();
		strand.setSort(lowerSort);
		lower.setSort(strandSort);
		session.update(strand);
		session.update(lower);
	}

	@SuppressWarnings("unchecked")
	public List<Scene> findScenes(Strand strand) {
		Query query = session
				.createQuery("select s from Scene as s left join s.chapter as ch"
						+ " where s.strand=:strand"
						+ " order by ch.chapterno, s.sceneno");
		query.setEntity(DAOutil.STRAND, strand);
		return (List<Scene>) query.list();
	}

	public int getNextSort() {
		return getMaxSort() + 1;
	}

	public int getMaxSort() {
		Query query = session.createQuery("select max(sort) from Strand");
		return (Integer) query.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public boolean checkIfNumberExists(AbstractEntity entity) {
		try {
			Strand newStrand = (Strand) entity;
			Integer newSort = newStrand.getSort();

			if (!entity.isTransient()) {
				// update
				StrandDAO dao = new StrandDAO(session);
				Strand oldStrand = dao.find(entity.getId());
				Integer oldSort = oldStrand.getSort();
				Criteria crit = session.createCriteria(Strand.class);
				crit.add(Restrictions.eq(DAOutil.SORT, newSort));
				List<Strand> strands = (List<Strand>) crit.list();
				List<Integer> numbers = new ArrayList<>();
				for (Strand strand : strands) {
					numbers.add(strand.getSort());
				}
				if (newSort.equals(oldSort)) {
					numbers.remove(newSort);
				}
				return numbers.isEmpty();
			}

			// new
			Criteria crit = session.createCriteria(Strand.class);
			crit.add(Restrictions.eq(DAOutil.SORT, newSort));
			List<Strand> strands = (List<Strand>) crit.list();
			return strands.isEmpty();
		} catch (NonUniqueResultException e) {
			ExceptionDlg.show(this.getClass().getSimpleName()
					+ ".checkIfNumberExists(entity=" + LOG.trace(entity)
					+ ") NonUniqueResultException", e);
			return true;
		}
	}

}

interface StrandDAOInterface extends GenericDAO<Strand, Long> {
}
