/*
 * Copyright (C) 2023 favdb
 *
 * 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.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import static storybook.model.EntityUtil.findEntities;
import storybook.model.Model;
import storybook.model.book.Book;
import storybook.model.hbn.dao.ChapterDAO;
import storybook.tools.ListUtil;
import storybook.tools.comparator.ObjectComparator;
import storybook.ui.MainFrame;

/**
 * Chapter utilities
 *
 * @author favdb
 */
public class Chapters {

	private Chapters() {
		//empty
	}

	/**
	 * find the Chapters list of the given Part
	 *
	 * @param mainFrame
	 * @param part
	 * @return
	 */
	public static List<Chapter> find(MainFrame mainFrame, Part part) {
		Model model = mainFrame.getBookModel();
		Session session = model.beginTransaction();
		List<Chapter> list = new ChapterDAO(session).findAll(part);
		model.commit();
		return list;
	}

	/**
	 * find dates for the given Chapter
	 *
	 * @param mainFrame
	 * @param chapter
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Date> findDates(MainFrame mainFrame, Chapter chapter) {
		List<Date> dates = new ArrayList<>();
		List<Scene> scenes = Scenes.findBy(mainFrame, chapter);
		for (Scene s : scenes) {
			dates.add(s.getDate());
		}
		dates = ListUtil.setUnique(dates);
		Collections.sort(dates, new ObjectComparator());
		return dates;
	}

	/**
	 * get the last used Chapter number
	 *
	 * @param mainFrame
	 * @return
	 */
	public static int getLastNumber(MainFrame mainFrame) {
		@SuppressWarnings("unchecked")
		List<Chapter> list = findEntities(mainFrame, Book.TYPE.CHAPTER);
		int n = 0;
		for (Chapter chapter : list) {
			if ((chapter.getChapterno() != null) && (chapter.getChapterno() > n)) {
				n = chapter.getChapterno();
			}
		}
		return n;
	}

}
