/*
 * 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.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.PartDAO;
import storybook.ui.MainFrame;

/**
 *
 * @author favdb
 */
public class Parts {

	private Parts() {
		//empty
	}

	/**
	 * get the first Part
	 *
	 * @param mainFrame
	 * @return
	 */
	public static Part getFirst(MainFrame mainFrame) {
		@SuppressWarnings("unchecked")
		List<Part> lst = findEntities(mainFrame, Book.TYPE.PART);
		return (lst.isEmpty() ? (Part) null : lst.get(0));
	}

	/**
	 * find the Parts list
	 *
	 * @param mainFrame
	 * @return
	 */
	public static List<Part> find(MainFrame mainFrame) {
		Model model = mainFrame.getBookModel();
		Session session = model.beginTransaction();
		List<Part> list = new PartDAO(session).findAll();
		model.commit();
		return list;
	}

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

}
