/* 
 * Copyright (C) 2001-2013 Michael Fuchs
 *
 * This file is part of herold.
 * 
 * herold 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.
 * 
 * herold 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 herold.  If not, see <http://www.gnu.org/licenses/>.  
 */
package org.dbdoclet.trafo.internal.html.docbook;

import java.util.HashMap;

import org.dbdoclet.tag.docbook.DocBookElement;
import org.dbdoclet.tag.docbook.DocBookTagFactory;
import org.dbdoclet.tag.docbook.Entrytbl;
import org.dbdoclet.tag.docbook.Informaltable;
import org.dbdoclet.tag.docbook.Tgroup;
import org.dbdoclet.tag.docbook.Xref;

public class PostprocessStage3 {

	private final DocBookTagFactory dbfactory;
	private final HashMap<Entrytbl, DocBookElement> subtables;

	public PostprocessStage3(DocBookTagFactory dbfactory,
			HashMap<Entrytbl, DocBookElement> subtables) {

		this.dbfactory = dbfactory;
		this.subtables = subtables;
	}

	public void process() {

		if ((subtables != null) && (subtables.size() > 0)) {

			int index = 1;

			for (Entrytbl entrytbl : subtables.keySet()) {

				String id = "subtable." + index;
				Xref xref = dbfactory.createXref(id);

				DocBookElement table = subtables.get(entrytbl);

				DocBookElement entryTblParent = (DocBookElement) entrytbl
						.getParentNode();

				entryTblParent.replaceChild(dbfactory.createEntry()
						.appendChild(xref), entrytbl);

				Informaltable it = dbfactory.createInformaltable();
				it.setId(id);
				it.setXrefLabel("#" + index);

				Tgroup tgroup = dbfactory.createTgroup();
				tgroup.setChildNodes(entrytbl.getChildNodes());
				tgroup.setTrafoAttributes(entrytbl.getAttributesAsMap());
				it.appendChild(tgroup);

				DocBookElement tableParent = (DocBookElement) table
						.getParentNode();

				if (tableParent != null) {
					tableParent.insertAfter(it, table);
				}

				index++;
			}
		}

	}
}
