/*
 * Copyright (C) 2017 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.ui.dialog.preferences;

import api.mig.swing.MigLayout;
import api.shef.ShefEditor;
import i18n.I18N;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Calendar;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.hibernate.Session;
import resources.icons.ICONS;
import storybook.App;
import storybook.Pref;
import storybook.exim.exporter.ExportToPhpBB;
import storybook.model.Model;
import storybook.model.book.Book;
import storybook.model.book.BookInfo;
import storybook.model.book.BookUtil;
import storybook.model.hbn.dao.AttributeDAO;
import storybook.model.hbn.dao.CategoryDAO;
import storybook.model.hbn.dao.ChapterDAO;
import storybook.model.hbn.dao.EndnoteDAO;
import storybook.model.hbn.dao.EventDAO;
import storybook.model.hbn.dao.GenderDAO;
import storybook.model.hbn.dao.IdeaDAO;
import storybook.model.hbn.dao.InternalDAO;
import storybook.model.hbn.dao.ItemDAO;
import storybook.model.hbn.dao.ItemlinkDAO;
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.PlotDAO;
import storybook.model.hbn.dao.RelationDAO;
import storybook.model.hbn.dao.SceneDAO;
import storybook.model.hbn.dao.StrandDAO;
import storybook.model.hbn.dao.TagDAO;
import storybook.model.hbn.dao.TaglinkDAO;
import storybook.model.hbn.entity.AbstractEntity;
import storybook.model.hbn.entity.Internal;
import storybook.model.hbn.entity.Scene;
import storybook.tools.DateUtil;
import storybook.tools.html.CSS;
import storybook.tools.html.Html;
import storybook.tools.swing.SwingUtil;
import storybook.tools.swing.js.JSLabel;
import storybook.ui.MIG;
import storybook.ui.MainFrame;
import storybook.ui.Ui;
import static storybook.ui.Ui.BMANDATORY;
import storybook.ui.dialog.AbstractDialog;
import static storybook.ui.panel.AbstractPanel.*;
import storybook.ui.review.Review;

/**
 *
 * @author favdb
 */
public class PropertiesDlg extends AbstractDialog implements ChangeListener {

	private static final String TT = "PropertiesDlg";

	public JTextField tfTitle;
	public JTextField tfSubtitle;
	public JTextField tfAuthor;
	public JTextArea taNotes;
	public JTextArea taBlurb;
	public JTextField tfCopyright;
	private JCheckBox ckUseNonModalEditors;
	private JTextPane tpFileInfo;
	//TODO calendar
	//private JCheckBox ckUseCalendar;
	public JCheckBox ckScenario;
	public JCheckBox ckMarkdown;
	private EpubPanel tbEpub;
	private BookLayoutPanel layoutPanel;
	private boolean bScenario;
	private boolean bMarkdown;
	private final boolean bNew;//are these properties for a new file
	private JComboBox cbNature;
	private AssistantBookPanel assistantPanel;
	private int origin;
	private PropXEditor tbEditor;
	private JComboBox cbSceneDateInit;
	private ShefEditor hDedication;
	private JButton btInitPhp;
	private JTabbedPane tabbedPane;
	private JPanel tbProject;
	private JPanel tbDedication;
	private JPanel tbAssistant;
	private JPanel tbWorking;
	private JPanel tbBookLayout;

	public static void show(MainFrame mainFrame) {
		PropertiesDlg dlg = new PropertiesDlg(mainFrame, false);
		dlg.setVisible(true);
	}

	public PropertiesDlg(MainFrame m, boolean bNew) {
		super(m);
		this.bNew = bNew;
		this.setModal(true);
		initAll();
	}

	@Override
	public void init() {
		origin = computeHash();
	}

	private int computeHash() {
		int hash = book.param.getParamLayout().getHashCode();
		return hash;
	}

	@Override
	public void initUi() {
		super.initUi();
		setLayout(new MigLayout("wrap,fill", "[][]"));
		setTitle(I18N.getMsg("properties.title"));
		tabbedPane = new JTabbedPane();
		tbProject = initProject();
		tabbedPane.addTab(I18N.getMsg("properties"), tbProject);
		tbDedication = initDedication();
		tabbedPane.addTab(I18N.getMsg("book.dedication"), tbDedication);
		initUiForMainframe();
		Dimension dim = new Dimension(800, 600);
		tabbedPane.setPreferredSize(dim);
		tabbedPane.setMaximumSize(SwingUtil.getScreenSize());
		add(tabbedPane, MIG.get(MIG.GROW, MIG.SPAN));
		btInitPhp = Ui.initButton("btInit", "export.phpbb", ICONS.K.COGS, "", e -> getInitPhpBB());
		add(btInitPhp);
		btInitPhp.setVisible(App.preferences.getBoolean(Pref.KEY.EXP_PHPBB));
		JPanel pOK = new JPanel(new MigLayout());
		pOK.add(getOkButton());
		pOK.add(getCancelButton());
		add(pOK, MIG.RIGHT);
		pack();
		setLocationRelativeTo(mainFrame);
	}

	private void initUiForMainframe() {
		if (mainFrame != null) {
			tbWorking = initTravail();
			tabbedPane.addTab(I18N.getMsg("preferences.global"), tbWorking);
			tbAssistant = initAssistant();
			if (tbAssistant.isVisible()) {
				tabbedPane.addTab(I18N.getMsg("assistant.title"), tbAssistant);
			}
			tbBookLayout = initBookLayout();
			tabbedPane.addTab(I18N.getMsg("book.layout"), tbBookLayout);
			tbEpub = new EpubPanel(mainFrame, this);
			tabbedPane.addTab(I18N.getMsg("epub.title"), tbEpub);
			tabbedPane.addTab(I18N.getMsg("file.info"), initFileInfo());
			if (App.isDev()) {
				tabbedPane.addTab("All properties", new JScrollPane(initAllProperties()));
			}
		}
	}

	private void getInitPhpBB() {
		StringBuilder b = new StringBuilder();
		b.append(Html.intoB(I18N.getColonMsg("book.title"))).append(" ")
		   .append(book.getTitle()).append("\n");
		if (!book.getSubtitle().isEmpty()) {
			b.append(Html.intoB(I18N.getColonMsg("book.title"))).append(" ")
			   .append(book.getTitle()).append("\n");
		}
		if (book.info.getNature() > 0) {
			String nature = "";
			String x = I18N.getMsg("book.nature." + book.info.getNature());
			if (!x.startsWith("!")) {
				nature = x.substring(0, x.indexOf(":")).trim();
			}
			b.append(Html.intoB(I18N.getColonMsg("book.nature"))).append(" ")
			   .append(nature).append("\n");
		}
		if (!book.info.getBlurb().isEmpty()) {
			b.append(Html.intoB(I18N.getColonMsg("book.blurb"))).append(" ")
			   .append(book.info.getBlurb()).append("\n");
		}
		ExportToPhpBB.getInit(b.toString());
	}

	/**
	 * initialize project properties: scenario, type, title, subtitle, author, copyright, blob,
	 * notes, markdown
	 *
	 * @return
	 */
	private JPanel initProject() {
		JPanel panel = new JPanel();
		panel.setLayout(new MigLayout(MIG.WRAP, "[right][grow]"));

		ckScenario = Ui.initCheckBox(null, "scenario", "scenario", false, BMANDATORY);
		panel.add(ckScenario, MIG.get(MIG.SKIP));
		panel.add(new JLabel(I18N.getColonMsg("book.nature")), MIG.RIGHT);
		cbNature = initCbNature();
		panel.add(cbNature);

		panel.add(new JLabel(I18N.getColonMsg("book.title")));
		tfTitle = new JTextField();
		panel.add(tfTitle, MIG.GROWX);
		panel.add(new JLabel(I18N.getColonMsg("book.subtitle")));
		tfSubtitle = new JTextField();
		panel.add(tfSubtitle, MIG.GROWX);
		panel.add(new JLabel(I18N.getColonMsg("book.author")));
		tfAuthor = new JTextField();
		panel.add(tfAuthor, MIG.GROWX);
		panel.add(new JLabel(I18N.getColonMsg("book.copyright")));
		tfCopyright = new JTextField();
		panel.add(tfCopyright, MIG.GROWX);
		panel.add(new JLabel(I18N.getColonMsg("book.blurb")), "top");
		taBlurb = new JTextArea();
		taBlurb.setLineWrap(true);
		taBlurb.setWrapStyleWord(true);
		JScrollPane scroll = new JScrollPane(taBlurb);
		SwingUtil.setMaxPreferredSize(scroll);
		panel.add(scroll, MIG.GROW);
		panel.add(new JLabel(I18N.getColonMsg("notes")), "top");
		taNotes = new JTextArea();
		taNotes.setLineWrap(true);
		taNotes.setWrapStyleWord(true);
		JScrollPane scroller = new JScrollPane(taNotes);
		SwingUtil.setMaxPreferredSize(scroller);
		panel.add(scroller, MIG.GROW);
		panel.add(new JSLabel(""));
		ckMarkdown = Ui.initCheckBox(null, "markdown", "markdown", false, BMANDATORY);
		panel.add(ckMarkdown, MIG.get(MIG.SPAN, MIG.RIGHT));
		if (mainFrame != null) {
			setTextfield(tfTitle, Book.INFO.TITLE);
			setTextfield(tfSubtitle, Book.INFO.SUBTITLE);
			setTextfield(tfAuthor, Book.INFO.AUTHOR);
			setTextfield(tfCopyright, Book.INFO.COPYRIGHT);
			setTextArea(taNotes, Book.INFO.NOTES);
			taNotes.setCaretPosition(0);
			setTextArea(taBlurb, Book.INFO.BLURB);
			taBlurb.setCaretPosition(0);
			bScenario = book.isScenario();
			ckScenario.setSelected(bScenario);
			bMarkdown = book.isMarkdown();
			ckMarkdown.setSelected(bMarkdown);
		}
		ckScenario.addChangeListener(this);
		return panel;
	}

	@SuppressWarnings("unchecked")
	public static JComboBox initCbNature() {
		//LOG.trace(TT + ".initCbNature()");
		JComboBox cb = new JComboBox();
		cb.setName("cbNature");
		int i = 0;
		while (true) {
			String x = I18N.getMsg("book.nature." + i);
			if (x.startsWith("!")) {
				break;
			}
			cb.addItem(x.substring(0, x.indexOf(":")).trim());
			i++;
		}
		return cb;
	}

	private JPanel initAllProperties() {
		JPanel panel = new JPanel(new MigLayout(MIG.WRAP, "[][grow]", "[][][grow][grow]"));
		Model model = mainFrame.getBookModel();
		@SuppressWarnings("null")
		Session session = model.beginTransaction();
		InternalDAO dao = new InternalDAO(session);
		List<Internal> internals = dao.findAll();
		for (Internal internal : internals) {
			panel.add(new JSLabel(internal.getKey()));
			StringBuilder b = new StringBuilder();
			if (internal.hasStringValue()) {
				b.append("String=\"").append(internal.getStringValue()).append("\"");
			} else if (internal.hasIntegerValue()) {
				b.append("Integer=\"").append(internal.getIntegerValue().toString()).append("\"");
			} else if (internal.hasBooleanValue()) {
				b.append("Boolean=\"").append(internal.getBooleanValue().toString()).append("\"");
			} else if (internal.hasBinValue()) {
				b.append("Byte nb=").append(internal.getBinValue().length);
			} else {
				b.append("unknown type or empty value");
			}
			panel.add(new JSLabel(b.toString()));
		}
		model.commit();
		return panel;
	}

	@Override
	public MainFrame getMainFrame() {
		return (mainFrame);
	}

	private void initSceneDate(JPanel p) {
		p.add(new JLabel(I18N.getColonMsg("date.init")), MIG.SPLIT2);
		cbSceneDateInit = Ui.initComboBox("cbSceneDateInit",
		   "date.init",
		   new String[]{"date.init.empty", "date.init.last", "date.init.today"},
		   1, !EMPTY, !ALL);
		cbSceneDateInit.setSelectedIndex(
		   book.getInteger(Book.PARAM.SCENE_DATE_INIT, 1));
		p.add(cbSceneDateInit);
	}

	private void initModalEditors(JPanel p) {
		/*ckUseNonModalEditors = Ui.initCheckBox(null,
				"ckUseNonModalEditors",
				"editors.nonmodal",
				book.param.getParamEditor().getModless(),
				!MANDATORY);
		ckUseNonModalEditors.setEnabled(false);
		p.add(ckUseNonModalEditors, MIG.WRAP);*/
	}

	/*
	private void initReplaceDiv(JPanel p) {
		JButton bt = new JButton(I18N.getMsg("properties.replace_div"));
		bt.setName("btReplaceDiv");
		bt.addActionListener(this);
		p.add(bt, MIG.get(MIG.SPAN, MIG.WRAP));
	}
	 */
 /*
	private void initCalendar(JPanel p) {
		//TODO calendar
	}
	 */
	/**
	 * initialize Travail properties: scenes date, external editor
	 *
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private JPanel initTravail() {
		JPanel p = new JPanel(new MigLayout(MIG.get(MIG.FILLX, MIG.HIDEMODE2, MIG.WRAP)));
		initSceneDate(p);
		p.add(Review.Properties(mainFrame));
		initModalEditors(p);
		tbEditor = new PropXEditor(mainFrame);
		p.add(tbEditor, MIG.GROWX);
		//initCalendar(p);
		/*if (App.isDev()) {
			p.add(new JLabel("schéma narratif à choix unique :"), MIG.SPLIT2);
			JComboBox freytag = new JComboBox();
			freytag.addItem("");
			freytag.addItem("schéma classique");
			freytag.addItem("schéma actantiel");
			freytag.addItem("schéma quinaire");
			freytag.addItem("les 36 situations dramatiques");
			freytag.addItem("le voyage du héros");// en 5 actes
			freytag.addItem("la pyramide de Freytag");
			// in https://publiersonlivre.fr/diagnostic-accompagnement-litteraire/schema-narratif-structures-de-recit/
			freytag.addItem("la feuille de rythme");// en 12 étapes
			freytag.addItem("la courbe de Fichtean");// en 8 éléments
			p.add(freytag, MIG.SPAN);
			JPanel px = new JPanel(new MigLayout(MIG.get(MIG.FILLX, MIG.WRAP + "3")));
			px.setBorder(BorderFactory.createTitledBorder("schéma narratif à choix multiple"));
			px.add(new JCheckBox("schéma classique"));
			px.add(new JCheckBox("schéma actantiel"));
			px.add(new JCheckBox("schéma quinaire"));
			px.add(new JCheckBox("36 situations"));
			px.add(new JCheckBox("voyage du héros"));
			px.add(new JCheckBox("pyramide de Freytag"));
			px.add(new JCheckBox("feuille de rythme"));
			px.add(new JCheckBox("courbe de Fichtean"));
			px.add(new JCheckBox("autre"));
			p.add(px, MIG.SPAN);
		}*/
		JPanel ps = new JPanel(new MigLayout(MIG.FILL));
		JScrollPane scroll = new JScrollPane(p);
		SwingUtil.setMaxPreferredSize(scroll);
		ps.add(scroll);
		return ps;
	}

	/**
	 * initialize book layout: part title, chapter title..., scene title..., reread comments
	 *
	 * @return
	 */
	private JPanel initBookLayout() {
		JPanel p = new JPanel(new MigLayout(MIG.get(MIG.FILLX, MIG.WRAP + " 2")));
		layoutPanel = new BookLayoutPanel(book.getParam().getParamLayout(), true);
		p.add(layoutPanel);
		JPanel ps = new JPanel(new MigLayout(MIG.FILL));
		JScrollPane scroll = new JScrollPane(p);
		SwingUtil.setMaxPreferredSize(scroll);
		ps.add(scroll);
		return (ps);
	}

	/**
	 * initialize dedication
	 *
	 * @return
	 */
	private JPanel initDedication() {
		JPanel p = new JPanel(new MigLayout(MIG.get(MIG.WRAP, MIG.FILL), "", "[grow]"));
		hDedication = new ShefEditor("", "none", book.getDedication());
		hDedication.setName("book.dedication");
		hDedication.setMinimumSize(new Dimension(200, 80));
		hDedication.setPreferredSize(new Dimension(800, 600));
		hDedication.setMaximumSize(new Dimension(1600, 1200));
		p.add(hDedication);
		return p;
	}

	/**
	 * initialize assistant usage
	 *
	 * @return
	 */
	private JPanel initAssistant() {
		JPanel p = new JPanel(new MigLayout(MIG.get(MIG.FLOWX, MIG.HIDEMODE3, MIG.WRAP), "[grow]"));
		assistantPanel = new AssistantBookPanel(this, mainFrame);
		JScrollPane sc = new JScrollPane(assistantPanel);
		p.add(sc, MIG.get(MIG.SPAN, MIG.GROW));
		return (p);
	}

	/**
	 * initialize file informations
	 *
	 * @return
	 */
	private JPanel initFileInfo() {
		JPanel p = new JPanel(new MigLayout(MIG.get(MIG.WRAP, MIG.FILL), "", "[grow]"));
		int textLength = BookUtil.getNbChars(mainFrame);
		int words = BookUtil.getNbWords(mainFrame);
		Session session = mainFrame.getBookModel().beginTransaction();
		File file = mainFrame.getH2File().getFile();
		StringBuilder buf = new StringBuilder();
		buf.append(Html.HTML_B);
		buf.append(CSS.getHeadWithCss(mainFrame.getFont()));
		buf.append(Html.BODY_B).append(Html.TABLE_B);
		buf.append(Html.getRow2Cols("file.info.filename", file.toString()));
		buf.append(Html.getRow2Cols("file.info.creation", book.getCreation()));
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(file.lastModified());
		buf.append(Html.getRow2Cols("file.info.last.mod", DateUtil.calendarToString(cal)));
		String size
		   = String.format("%,d %s (%,d %s) => %d %s",
			  words, I18N.getMsg("words"),
			  textLength, I18N.getMsg("characters"),
			  words / 480, I18N.getMsg("pages"));
		//nb de pages sur la base de 480 mots par page
		buf.append(Html.getRow2Cols("file.info.text.length", size));
		buf.append(Html.getRow2Cols("strands", new StrandDAO(session).count(null)));
		buf.append(Html.getRow2Cols("parts", new PartDAO(session).count(null)));
		buf.append(Html.getRow2Cols("chapters", new ChapterDAO(session).count(null)));
		buf.append(Html.getRow2Cols("scenes", new SceneDAO(session).count(null)));
		buf.append(Html.getRow2Cols("persons", new PersonDAO(session).count(null)));
		buf.append(Html.getRow2Cols("locations", new LocationDAO(session).count(null)));
		buf.append(Html.getRow2Cols("items", new ItemDAO(session).count(null)));
		buf.append(Html.getRow2Cols("tags", new TagDAO(session).count(null)));
		buf.append(Html.getRow2Cols("endnotes", new EndnoteDAO(session).count(null)));
		buf.append(Html.getRow2Cols("events", new EventDAO(session).count(null)));
		buf.append(Html.getRow2Cols("ideas", new IdeaDAO(session).count(null)));
		buf.append(Html.getRow2Cols("memos", new MemoDAO(session).count(null)));
		buf.append(Html.TABLE_E)
		   .append(Html.BODY_E)
		   .append(Html.HTML_E);
		mainFrame.getBookModel().commit();
		tpFileInfo = new JTextPane();
		tpFileInfo.setEditable(false);
		tpFileInfo.setContentType(Html.TYPE);
		tpFileInfo.setText(buf.toString());
		tpFileInfo.setCaretPosition(0);
		JScrollPane scroller = new JScrollPane();
		scroller.setViewportView(tpFileInfo);
		p.add(scroller, MIG.GROW);
		return (p);
	}

	private void setTextfield(JTextField tx, Book.INFO key) {
		tx.setText(book.getString(key));
	}

	private void setTextArea(JTextArea tx, Book.INFO key) {
		tx.setText(book.getString(key));
		tx.setCaretPosition(0);
	}

	private boolean verify() {
		String rc = BookInfo.isDataOK(tfTitle.getText(),
		   tfSubtitle.getText(),
		   tfAuthor.getText(),
		   tfCopyright.getText());
		if (!rc.isEmpty()) {
			tabbedPane.setSelectedComponent(tbProject);
			showError(rc);
			return false;
		}
		rc = tbEditor.verify();
		if (!rc.isEmpty()) {
			tabbedPane.setSelectedComponent(tbWorking);
			showError(rc);
			return false;
		}
		return true;
	}

	private void showError(String rc) {
		JOptionPane.showMessageDialog(this, rc, I18N.getMsg("error"), JOptionPane.OK_OPTION);
	}

	@Override
	protected AbstractAction getOkAction() {
		return new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (verify()) {
					apply();
				}
			}
		};
	}

	private void apply() {
		if (mainFrame == null) {
			dispose();
			return;
		}
		//book info : title, subtitle, author, copyright, blurb, notes, scenario,markdown, nature
		book.info.setTitle(tfTitle.getText());
		book.info.setSubtitle(tfSubtitle.getText());
		book.info.setAuthor(tfAuthor.getText());
		book.info.setCopyright(tfCopyright.getText());
		book.info.setBlurb(taBlurb.getText());
		book.info.setNotes(taNotes.getText());
		book.info.setDedication(hDedication.getText());
		// if not new file and markdown change then convert all text
		if (!bNew && ckMarkdown.isSelected() != bMarkdown) {
			BookUtil.convertTo(mainFrame, !bMarkdown);
		}
		book.info.setMarkdown(ckMarkdown.isSelected());
		book.info.scenarioSet(ckScenario.isSelected());
		book.info.setNature(cbNature.getSelectedIndex());

		//TODO calendar
		if (ckUseNonModalEditors != null) {
			book.param.getParamEditor().setModless(ckUseNonModalEditors.isSelected());
		}
		book.setInteger(Book.PARAM.SCENE_DATE_INIT, cbSceneDateInit.getSelectedIndex());

		// book assistant, epub, layout
		assistantPanel.apply();
		tbEpub.apply();
		layoutPanel.apply();
		tbEditor.apply();

		SwingUtil.setWaitingCursor(this);
		book.save();
		mainFrame.setUpdated();

		//refresh all only if origin hash differe
		/*if (origin != computeHash()) {
			mainFrame.refresh();
		}*/
		SwingUtil.setDefaultCursor(this);
		dispose();
	}

	public void setSettings() {
		if (book != null) {
			book.setProperties(this);
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() instanceof JButton) {
			JButton bt = (JButton) e.getSource();
			if (bt.getName().equals("btReplaceDiv")) {
				Session session = mainFrame.getBookModel().beginTransaction();
				for (Book.TYPE type : Book.getTypes()) {
					replaceHtmlDiv(session, type);
				}
				mainFrame.getBookModel().commit();
			}
		}
	}

	private void replaceHtmlDiv(Session session, Book.TYPE type) {
		List entities = null;
		switch (type) {
			case ATTRIBUTE:
				entities = new AttributeDAO(session).findAll();
				break;
			case CATEGORY:
				entities = new CategoryDAO(session).findAll();
				break;
			case CHAPTER:
				entities = new ChapterDAO(session).findAll();
				break;
			case ENDNOTE:
				entities = new EndnoteDAO(session).findAll();
				break;
			case EVENT:
				entities = new EventDAO(session).findAll();
				break;
			case GENDER:
				entities = new GenderDAO(session).findAll();
				break;
			case IDEA:
				entities = new IdeaDAO(session).findAll();
				break;
			case ITEM:
				entities = new ItemDAO(session).findAll();
				break;
			case ITEMLINK:
				entities = new ItemlinkDAO(session).findAll();
				break;
			case LOCATION:
				entities = new LocationDAO(session).findAll();
				break;
			case MEMO:
				entities = new MemoDAO(session).findAll();
				break;
			case PART:
				entities = new PartDAO(session).findAll();
				break;
			case PERSON:
				entities = new PersonDAO(session).findAll();
				break;
			case PLOT:
				entities = new PlotDAO(session).findAll();
				break;
			case RELATION:
				entities = new RelationDAO(session).findAll();
				break;
			case SCENE:
				entities = new SceneDAO(session).findAll();
				break;
			case STRAND:
				entities = new StrandDAO(session).findAll();
				break;
			case TAG:
				entities = new TagDAO(session).findAll();
				break;
			case TAGLINK:
				entities = new TaglinkDAO(session).findAll();
				break;
			default:
				break;
		}
		if (entities == null) {
			return;
		}
		String div = "div", p = "p";
		for (Object entity : entities) {
			AbstractEntity en = (AbstractEntity) entity;
			if (type == Book.TYPE.SCENE) {
				((Scene) en).setSummary(Html.replaceTags(((Scene) en).getSummary(), div, p));
			}
			en.setDescription(Html.replaceTags(en.getDescription(), div, p));
			en.setNotes(Html.replaceTags(en.getNotes(), div, p));
			mainFrame.getBookController().updateEntity(en);
		}
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		if (e.getSource() instanceof JCheckBox) {
			JCheckBox ck = (JCheckBox) e.getSource();
			if (ck.getName().equals("scenario") && ck.isSelected()) {
				ckMarkdown.setSelected(true);
			} else {
				ckMarkdown.setSelected(bMarkdown);
			}
		}
	}

	public PropXEditor getXeditor() {
		return tbEditor;
	}

}
