/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2008 jOpenDocument, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU
 * General Public License Version 3 only ("GPL").  
 * You may not use this file except in compliance with the License. 
 * You can obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.html
 * See the License for the specific language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 * 
 */

/*
 * Cell created on 10 décembre 2005
 */
package org.jopendocument.dom.spreadsheet;

import org.jopendocument.dom.NS;
import org.jopendocument.dom.OOUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.jdom.Element;
import org.jdom.Namespace;

/**
 * A cell in a calc document. If you want to change a cell value you must obtain a MutableCell.
 * 
 * @author Sylvain
 */
public class Cell extends CalcNode {

    // as per 16.1 "Data Types" and 6.7.1 "Variable Value Types and Values"
    // see http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#isoformats

    // time means Duration for OpenDocument (see 6.7.1)
    static protected final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("'PT'HH'H'mm'M'ss'S'");
    static protected final SimpleDateFormat OODateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH':'mm':'ss");

    static final Element createEmpty(NS ns) {
        return createEmpty(ns, 1);
    }

    static final Element createEmpty(NS ns, int count) {
        final Element e = new Element("table-cell", ns.getTABLE());
        if (count > 1)
            e.setAttribute("number-columns-repeated", count + "", ns.getTABLE());
        return e;
    }

    protected final Row parent;

    Cell(Row parent, Element elem) {
        super(elem);
        this.parent = parent;
    }

    protected final NS getNS() {
        return this.parent.getSheet().getSpreadSheet().getNS();
    }

    protected final Namespace getValueNS() {
        return this.getNS().getVersion().equals(OOUtils.OD) ? this.getNS().getOFFICE() : this.getNS().getTABLE();
    }

    protected final String getType() {
        return this.getElement().getAttributeValue("value-type", getValueNS());
    }

    public final String getStyle() {
        return this.getElement().getAttributeValue("style-name", getNS().getTABLE());
    }

    private final String getValue(String attrName) {
        return this.getElement().getAttributeValue(attrName, getValueNS());
    }

    public Object getValue() {
        if (this.getType() == null || this.getType().equals("string")) {
            // ATTN oo generates string value-types w/o any @string-value
            final String attr = this.getValue("string-value");
            if (attr != null)
                return attr;
            else {
                final Element child = this.getElement().getChild("p", getNS().getTEXT());
                // empty cell
                return child == null ? "" : child.getText();
            }
        } else if (this.getType().equals("float") || this.getType().equals("currency") || this.getType().equals("percentage")) {
            final String attr = this.getValue("value");
            return Float.valueOf(attr);
        } else if (this.getType().equals("date")) {
            final String attr = this.getValue("date-value");
            try {
                return OODateFormat.parse(attr);
            } catch (ParseException e) {
                // should not happen since we're writing with OODateFormat, and Calc writes ok too
                throw new IllegalStateException("invalid date");
            }
        } else if (this.getType().equals("time")) {
            // TODO handle setValue()
            final String attr = this.getValue("time-value");
            try {
                return TIME_FORMAT.parseObject(attr);
            } catch (ParseException e) {
                throw new IllegalStateException("invalid date");
            }
        } else {
            throw new IllegalStateException("unknown type: " + this.getType());
        }
    }

    public boolean isValid() {
        return !this.getElement().getName().equals("covered-table-cell");
    }

}