package net.sourceforge.ganttproject.io;

import javax.xml.transform.sax.TransformerHandler;

import net.sourceforge.ganttproject.gui.options.model.GPOption;
import net.sourceforge.ganttproject.gui.options.model.GPOptionGroup;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class SaverBase {
    protected void startElement(String name, TransformerHandler handler)
            throws SAXException {
        startElement(name, ourEmptyAttributes, handler);
    }

    protected void startElement(String name, AttributesImpl attrs,
            TransformerHandler handler) throws SAXException {
        handler.startElement("", name, name, attrs);
        attrs.clear();
    }

    protected void endElement(String name, TransformerHandler handler)
            throws SAXException {
        handler.endElement("", name, name);
    }

    protected void addAttribute(String name, String value, AttributesImpl attrs) {
        if (value!=null) { 
            attrs.addAttribute("", name, name, "CDATA", value);
        }
    }

    protected void addAttribute(String name, int value, AttributesImpl attrs) {
        addAttribute(name, String.valueOf(value), attrs);
    }
    
    protected void emptyElement(String name, AttributesImpl attrs,
            TransformerHandler handler) throws SAXException {
        startElement(name, attrs, handler);
        endElement(name, handler);
        attrs.clear();
    }

    protected void cdataElement(String name, String cdata, AttributesImpl attrs, TransformerHandler handler) throws SAXException {
        startElement(name, attrs, handler);
        handler.startCDATA();
        handler.characters(cdata.toCharArray(), 0, cdata.length());
        handler.endCDATA();
        endElement(name, handler);
    }
    protected void emptyComment(TransformerHandler handler) throws SAXException {
        handler.comment(new char[] { ' ' }, 0, 1);

    }
    protected void saveOptions(GPOptionGroup options, TransformerHandler handler) throws SAXException {
        startElement(options.getID(), handler);
        AttributesImpl attrs = new AttributesImpl();
        for (GPOption nextOption : options.getOptions()){
            if (nextOption.getPersistentValue()!=null) {
                addAttribute("id", nextOption.getID(), attrs);
                addAttribute("value", nextOption.getPersistentValue(), attrs);
                emptyElement("option", attrs, handler);
            }
        }    	
        endElement(options.getID(), handler);
    }
    protected void saveOptions(GPOptionGroup[] settings, TransformerHandler handler) throws SAXException {
        for (GPOptionGroup group : settings) {
            saveOptions(group, handler);
        }
    }
    private static AttributesImpl ourEmptyAttributes = new AttributesImpl();
}
