/*
 * $Revision: 1.2 $ $Date: 2006/05/11 15:36:07 $
 * Copyright (C) 2005 SUGIMOTO Ken-ichi
 * 作成日： 2005/7/29
 */

package feat2.template.impl;

import feat2.StringUtil;
import feat2.template.HTMLAttribute;
import feat2.template.HTMLNode;
import feat2.template.NodeNotFoundException;

/**
 * 値を持つ属性。
 */
public class HTMLValuedAttribute extends HTMLNodeImpl implements HTMLAttribute {

    private String name;
    private String value;
    private String quote;

    HTMLValuedAttribute(String name, String rawValue) {
        this.name = name;
        this.value = rawValue;
        this.quote = "\"";
        setDomNode(new DOMAttrImpl(this));
    }

    public String getName() {
        return name;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        setRawValue( value == null ? null : StringUtil.escapeHTMLText(value) );
    }

    public void setRawValue(String rawValue) {
        this.value = rawValue;
    }

    /**
     * 値を囲む文字を返す。
     * @return String
     */
    public String getQuote() {
        return quote;
    }

    /*public void setText(String str) {
        throw new UnsupportedOperationException();
    }*/

    /*public void addText(String str) {
        throw new UnsupportedOperationException();
    }*/

    public String toString() {
        return toHTML(new StringBuffer()).toString();
    }

    public void setFirstChild(HTMLNode child) {
    }

    // HTMLNodeの実装 -----------------------------------------------------------

    public HTMLNode getFirstChild() throws NodeNotFoundException {
        throw new NodeNotFoundException();
    }

    public StringBuffer toHTML(StringBuffer buf) {

        if ( name != null )
            buf.append(name);

        if ( name != null && value != null )
            buf.append("=");

        if ( value != null ) {

            String v;
            try {
                v = StringUtil.correctJapaneseChars(value, getDocument().getEncoding());
            }
            catch (NodeNotFoundException ex) {
                v = value;
            }

            if ( quote != null && quote.length() > 0 && !quote.equals("\u0000" ) )
                buf.append(quote).append(v).append(quote);
            else
                buf.append(v);

        }

        return buf;

    }

    public HTMLNode copy(boolean deep) {
        HTMLValuedAttribute ret = new HTMLValuedAttribute(name, value);
        ret.setQuote(quote);
        return ret;
    }

    public String getValue() {
        return StringUtil.unescapeHTMLText(value);
    }

    public int getNodeType() {
        return NODETYPE_ATTRIBUTE;
    }

}
