/*
 * Copyright 2013, 2014 Deutsche Nationalbibliothek
 *
 * Licensed under the Apache License, Version 2.0 the "License";
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metafacture.xml;

import java.util.regex.Pattern;

import org.metafacture.framework.FluxCommand;
import org.metafacture.framework.MetafactureException;
import org.metafacture.framework.StreamReceiver;
import org.metafacture.framework.XmlReceiver;
import org.metafacture.framework.annotations.Description;
import org.metafacture.framework.annotations.In;
import org.metafacture.framework.annotations.Out;
import org.metafacture.framework.helpers.DefaultXmlPipe;
import org.xml.sax.Attributes;


/**
 * A generic xml reader.
 *
 * @author Markus Michael Geipel
 *
 */
@Description("A generic xml reader")
@In(XmlReceiver.class)
@Out(StreamReceiver.class)
@FluxCommand("handle-generic-xml")
public final class GenericXmlHandler extends DefaultXmlPipe<StreamReceiver> {

    private static final Pattern TABS = Pattern.compile("\t+");
    private final String recordTagName;
    private boolean inRecord;
    private StringBuilder valueBuffer = new StringBuilder();

    public GenericXmlHandler() {
        super();
        this.recordTagName = System.getProperty(
                "org.culturegraph.metamorph.xml.recordtag");
        if (recordTagName == null) {
            throw new MetafactureException("Missing name for the tag marking a record.");
        }
    }

    public GenericXmlHandler(final String recordTagName) {
        super();
        this.recordTagName = recordTagName;
    }

    @Override
    public void startElement(final String uri, final String localName,
            final String qName, final Attributes attributes) {

        if (inRecord) {
            writeValue();
            getReceiver().startEntity(localName);
            writeAttributes(attributes);
        } else if (localName.equals(recordTagName)) {
            final String identifier = attributes.getValue("id");
            if (identifier == null) {
                getReceiver().startRecord("");
            } else {
                getReceiver().startRecord(identifier);
            }
            writeAttributes(attributes);
            inRecord = true;
        }
    }

    @Override
    public void endElement(final String uri, final String localName,
            final String qName) {
        if (inRecord) {
            writeValue();
            if (localName.equals(recordTagName)) {
                inRecord = false;
                getReceiver().endRecord();
            } else {
                getReceiver().endEntity();
            }
        }
    }

    @Override
    public void characters(final char[] chars, final int start, final int length) {
        if (inRecord) {
            valueBuffer.append(TABS.matcher(new String(chars, start, length))
                    .replaceAll(""));
        }
    }

    private void writeValue() {
        final String value = valueBuffer.toString();
        if (!value.trim().isEmpty()) {
            getReceiver().literal("value", value.replace('\n', ' '));
        }
        valueBuffer = new StringBuilder();
    }

    private void writeAttributes(final Attributes attributes) {
        final int length = attributes.getLength();

        for (int i = 0; i < length; ++i) {
            final String name = attributes.getLocalName(i);
            final String value = attributes.getValue(i);
            getReceiver().literal(name, value);
        }
    }

}

@@ -1383,24 +1383,87 @@
 eceiver%3E %7B%0A%0A
+    public static final String DEFAULT_RECORD_TAG = %22record%22;%0A%0A
     private 
@@ -1510,24 +1510,25 @@
 ile(%22%5Ct+%22);%0A
+%0A
     private 
@@ -1527,22 +1527,16 @@
 private 
-final 
 String r
@@ -1543,25 +1543,47 @@
 ecordTagName
-;
+ = DEFAULT_RECORD_TAG;%0A
 %0A    private
@@ -1713,37 +1713,45 @@
 uper();%0A        
-this.
+final String 
 recordTagName = 
@@ -1747,16 +1747,24 @@
 dTagName
+Property
  = Syste
@@ -1864,18 +1864,26 @@
 dTagName
- =
+Property !
 = null) 
@@ -1899,74 +1899,348 @@
     
- throw new MetafactureException(%22Missing name for th
+recordTagName = recordTagNameProperty;%0A        %7D%0A    %7D%0A%0A    /**%0A     * Creates a new %7B@ode GenericXmlReader%7D with the given tag name as%0A     * marker for records.%0A     *%0A     * @deprecated Use default constructor and set the tag name latter%0A     * with %7B@link #setRecordTagName(String)%7D.%0A     *%0A     * @param recordTagNam
 e tag 
+name 
 marking 
 a re
@@ -2235,16 +2235,29 @@
 marking 
+the start of 
 a record
@@ -2261,28 +2261,32 @@
 ord.
-%22);%0A  
+%0A
      
- %7D
+*/
 %0A    
-%7D%0A
+@Deprecated
 %0A   
@@ -2401,32 +2401,612 @@
 TagName;%0A    %7D%0A%0A
+    /**%0A     * Sets the tag name which marks the start of a record.%0A     * %3Cp%3E%0A     * This value may only be changed between records. If it is changed%0A     * while processing a record the behaviour of this module is undefined.%0A     * %3Cp%3E%0A     * %3Cstrong%3EDefault value: %7B@value DEFAULT_RECORD_TAG%7D%3C/strong%3E%0A     *%0A     * @param recordTagName the tag name which marks the start of a record.%0A     */%0A    public void setRecordTagName(String recordTagName) %7B%0A        this.recordTagName = recordTagName;%0A    %7D%0A%0A    public String getRecordTagName() %7B%0A        return recordTagName;%0A    %7D%0A%0A
     @Override%0A  

Add `setRecordTagName` property to `GenericXmlHandler`