/* 
 * 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.editor;

import org.dbdoclet.service.StringServices;
import org.dbdoclet.tag.docbook.Anchor;
import org.dbdoclet.tag.docbook.DocBookTagFactory;
import org.dbdoclet.tag.docbook.Indexterm;
import org.dbdoclet.tag.docbook.Primary;
import org.dbdoclet.tag.docbook.Secondary;
import org.dbdoclet.tag.html.Span;
import org.dbdoclet.trafo.html.EditorException;
import org.dbdoclet.trafo.html.EditorInstruction;
import org.dbdoclet.xiphias.dom.NodeImpl;

public class SpanEditor extends DocBookEditor {

	@Override
	public EditorInstruction edit(EditorInstruction values)
			throws EditorException {

		setValues(super.edit(values));
		DocBookTagFactory dbfactory = getTagFactory();

		Span span = (Span) getHtmlElement();
		NodeImpl parent = getParent();

		String title = span.getTitle();

		String border1 = ":primary=";
		String border2 = ":secondary=";

		if ((title != null) && title.startsWith("indexterm:")) {

			String buffer = StringServices.cutPrefix(title, "indexterm");

			if (buffer.startsWith(border1)) {

				String primaryText = StringServices.cutPrefix(buffer, border1);
				String secondaryText = null;

				int indexSecondary = primaryText.indexOf(border2);

				if (indexSecondary != -1) {

					int index = indexSecondary + border2.length();

					if (index < primaryText.length()) {

						secondaryText = primaryText.substring(indexSecondary
								+ border2.length());
					}

					primaryText = primaryText.substring(0, indexSecondary);
				}

				Indexterm indexTerm = dbfactory.createIndexterm();
				indexTerm.setParentNode(getParent());

				Primary primary = dbfactory.createPrimary(primaryText);
				indexTerm.appendChild(primary);

				if ((secondaryText != null) && (secondaryText.length() > 0)) {

					Secondary secondary = dbfactory
							.createSecondary(secondaryText);
					indexTerm.appendChild(secondary);
				}

				parent.appendChild(indexTerm);
			}
		}

		String id = span.getId();

		if (id != null) {

			Anchor anchor = dbfactory.createAnchor();
			anchor.setId(getLinkManager().createUniqueId(id));
			parent.appendChild(anchor);
		}

		traverse(true);

		return finalizeValues();
	}
}
