/*
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.Category;
import storybook.model.hbn.entity.Person;
import storybook.tools.LOG;
import storybook.ui.dialog.ExceptionDlg;

public class CategoryDAO extends _GenericDAO<Category, Long>
		implements CategoryDAOInterface {

	private static final String TT = "CategoryDAO";

	public CategoryDAO() {
		super();
	}

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

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

	public Category findCentral() {
		return (Category) session.get(Category.class, 1L);
	}

	public Category findMinor() {
		return (Category) session.get(Category.class, 2L);
	}

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

	public void orderCategories() {
		int i = 0;
		for (Category c : findAllOrderBySort()) {
			c.setSort(i);
			session.update(c);
			++i;
		}
	}

	public void orderUpCategory(Category category) {
		if (category.getSort() == 0) {
			return;
		}
		session.refresh(category);
		int categorySort = category.getSort();
		Criteria crit = session.createCriteria(Category.class);
		crit.add(Restrictions.eq("sort", category.getSort() - 1));
		Category upper = (Category) crit.uniqueResult();
		int upperSort = upper.getSort();
		category.setSort(upperSort);
		upper.setSort(categorySort);
		session.update(category);
		session.update(upper);
	}

	public void orderDownCategory(Category category) {
		session.refresh(category);
		int categorySort = category.getSort();
		Criteria crit = session.createCriteria(Category.class);
		crit.add(Restrictions.eq("sort", category.getSort() + 1));
		Category lower = (Category) crit.uniqueResult();
		if (lower == null) {
			return;
		}
		int lowerSort = lower.getSort();
		category.setSort(lowerSort);
		lower.setSort(categorySort);
		session.update(category);
		session.update(lower);
	}

	@SuppressWarnings("unchecked")
	public List<Person> findPersons(Category category) {
		Criteria crit = session.createCriteria(Person.class);
		crit.add(Restrictions.eq("category", category));
		List<Person> persons = (List<Person>) crit.list();
		return persons;
	}

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

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

	@SuppressWarnings("unchecked")
	public boolean checkIfNumberExists(AbstractEntity entity) {
		try {
			Category newCategory = (Category) entity;
			Integer newSort = newCategory.getSort();
			if (!entity.isTransient()) {
				// update
				CategoryDAO dao = new CategoryDAO(session);
				Category oldChapter = dao.find(entity.getId());
				Integer oldSort = oldChapter.getSort();
				Criteria crit = session.createCriteria(Category.class);
				crit.add(Restrictions.eq("sort", newSort));
				List<Category> categories = (List<Category>) crit.list();
				List<Integer> numbers = new ArrayList<>();
				for (Category category : categories) {
					numbers.add(category.getSort());
				}
				if (newSort.equals(oldSort)) {
					numbers.remove(newSort);
				}
				return (!numbers.isEmpty());
			}
			Criteria crit = session.createCriteria(Category.class);
			crit.add(Restrictions.eq("sort", newSort));
			List<Category> categories = (List<Category>) crit.list();
			return (!categories.isEmpty());
		} catch (NonUniqueResultException e) {
			ExceptionDlg.show(this.getClass().getSimpleName()
					+ ".checkIfNumberExists(entity=" + LOG.trace(entity) + ") NonUniqueResultException", e);
			return true;
		}
	}

}

interface CategoryDAOInterface extends GenericDAO<Category, Long> {
}
