/*
 * Copyright (C) 2021 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 fileCopy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package storybook.exim.exporter;

import assistant.Assistant;
import i18n.I18N;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.Session;
import storybook.exim.EXIM;
import storybook.model.EntityUtil;
import storybook.model.book.BookUtil;
import storybook.model.hbn.dao.ChapterDAO;
import storybook.model.hbn.dao.EndnoteDAO;
import storybook.model.hbn.dao.EventDAO;
import storybook.model.hbn.dao.IdeaDAO;
import storybook.model.hbn.dao.ItemDAO;
import storybook.model.hbn.dao.LocationDAO;
import storybook.model.hbn.dao.MemoDAO;
import storybook.model.hbn.dao.PartDAO;
import storybook.model.hbn.dao.PersonDAO;
import storybook.model.hbn.dao.SceneDAO;
import storybook.model.hbn.dao.StrandDAO;
import storybook.model.hbn.dao.TagDAO;
import storybook.model.hbn.entity.AbstractEntity;
import storybook.tools.LOG;
import storybook.tools.file.IOUtil;
import storybook.tools.html.Html;
import storybook.ui.MainFrame;
import storybook.ui.dialog.ExceptionDlg;
import storybook.ui.panel.info.InfoPanel;

/**
 * export the Info view data
 *
 * @author favdb
 */
public class ExportInfo extends AbstractExport {

	private static final String EXPORT_TITLE = "Info Export";

	private InfoPanel infoPanel;
	private AbstractEntity entity;

	public ExportInfo(MainFrame mainFrame) {
		super(mainFrame, "html");
	}

	private void writeSummary() {
		File file = mainFrame.getH2File().getFile();
		int textLength = BookUtil.getNbChars(mainFrame);
		int words = BookUtil.getNbWords(mainFrame);
		Session session = mainFrame.getBookModel().beginTransaction();
		//writeText(Html.BEGIN);
		//writeText(Html.getHeadWithCss(mainFrame.getFont()));
		//writeText(Html.BODY);
		writeText(Html.TABLE_B);
		writeText(Html.toHtml("file.info.filename", file.toString()));
		writeText(Html.toHtml("file.info.creation", book.getCreation()));
		writeText(Html.toHtml("file.info.maj", book.getMaj()));
		String size = String.format("%,d %s (%,d %s)", words, I18N.getMsg("words"), textLength, I18N.getMsg("characters"));
		writeText(Html.toHtml("book.title", book.getTitle()));
		writeText(Html.toHtml("book.subtitle", book.getSubtitle()));
		writeText(Html.toHtml("book.author", book.getAuthor()));
		writeText(Html.toHtml("book.copyright", book.getCopyright()));
		writeText(Html.toHtml("book.blurb", book.getBlurb()));
		if (!book.getUUID().isEmpty()) {
			writeText(Html.toHtml("book.UUID", book.getUUID()));
		}
		if (!book.getISBN().isEmpty()) {
			writeText(Html.toHtml("book.ISBN", book.getISBN()));
		}
		writeText(Html.toHtml("file.info.text.length", size));
		writeText(Html.toHtml("strands", new StrandDAO(session).count(null)));
		writeText(Html.toHtml("parts", new PartDAO(session).count(null)));
		writeText(Html.toHtml("chapters", new ChapterDAO(session).count(null)));
		writeText(Html.toHtml("scenes", new SceneDAO(session).count(null)));
		writeText(Html.toHtml("persons", new PersonDAO(session).count(null)));
		writeText(Html.toHtml("locations", new LocationDAO(session).count(null)));
		writeText(Html.toHtml("items", new ItemDAO(session).count(null)));
		writeText(Html.toHtml("tags", new TagDAO(session).count(null)));
		writeText(Html.toHtml("endnotes", new EndnoteDAO(session).count(null)));
		writeText(Html.toHtml("events", new EventDAO(session).count(null)));
		writeText(Html.toHtml("ideas", new IdeaDAO(session).count(null)));
		writeText(Html.toHtml("memos", new MemoDAO(session).count(null)));
		writeText(Html.toHtml("notes", book.getNotes()));
		if (!book.info.assistantGet().isEmpty()) {
			String str = Assistant.toHtml(book.info.assistantGet());
			writeText(Html.toHtml("assistant", str));
		}
		writeText(Html.TABLE_E);
		//writeText(Html.BODY_END);
		//writeText(Html.END);
		session.close();
	}

	public static boolean exec(MainFrame mainFrame, String type) {
		LOG.trace("ExportInfo.exec(mainFrame, type=\"" + type + "\")");
		if (type.equals("summary")) {
			ExportInfo exp = new ExportInfo(mainFrame);
			if (exp.openFile(I18N.getMsg("export.book.summary"), true)) {
				exp.writeSummary();
			}
			exp.closeFile(true);
			return true;
		}
		@SuppressWarnings("unchecked")
		List<AbstractEntity> entities = EntityUtil.findEntities(mainFrame, type);
		if (entities.isEmpty()) {
			return true;
		}
		ExportInfo exp = new ExportInfo(mainFrame);
		if (exp.openFile("info_" + I18N.getMsg(type), true)) {
			for (AbstractEntity entity : entities) {
				exp.writeText(entity.toDetail(3));
			}
			exp.closeFile(true);
			return true;
		}
		return false;
	}

	public boolean exec(InfoPanel infoPanel) {
		//App.trace("ExportInfo.exec(infoPanel)");
		this.infoPanel = infoPanel;
		this.entity = infoPanel.getEntity();
		// open the output file to write
		String fname = "info_" + I18N.getMsg(entity.getObjType().toString()) + "_" + entity.getName();
		fname = IOUtil.filenameCleanup(fname);
		if (openFile(fname, true)) {
			writeText(infoPanel.getInfoPane().getText());
			closeFile(true);
		}
		return true;
	}

	@Override
	public boolean openFile(String name, boolean askexists) {
		isOpened = false;
		param.setFileName(param.getDirectory() + File.separator + name + ".html");
		this.name = name;
		File file = new File(param.getDirectory());
		if (!(file.exists() && file.isDirectory()) && askexists) {
			JOptionPane.showMessageDialog(mainFrame,
					I18N.getMsg("export.dir.error"),
					I18N.getMsg("export"), 1);
			return false;
		}
		if (!EXIM.askExists(infoPanel, param.getFileName())) {
			return false;
		}
		try {
			outStream = new BufferedWriter(new FileWriter(param.getFileName()));
		} catch (IOException ex) {
			ExceptionDlg.show(this.getClass().getSimpleName()
					+ ".openFile(...) outStream error", ex);
			return (false);
		}
		isOpened = true;
		writeHeaderHtml();
		return true;
	}

}
