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

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

import org.jopendocument.dom.NS;
import org.jopendocument.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import org.jdom.Element;

/**
 * A row in a Calc document. This class will only break "repeated" attributes on demand (eg for
 * setting a value).
 * 
 * @author Sylvain
 */
public class Row extends CalcNode {

    static Element createEmpty(NS ns) {
        return new Element("table-row", ns.getTABLE());
    }

    private final Sheet parent;
    // immutable cells
    private final List<Cell> cells;

    public Row(Sheet parent, Element tableRowElem) {
        super(tableRowElem);
        this.parent = parent;
        this.cells = new ArrayList<Cell>();
        for (final Element cellElem : this.getCellElements()) {
            addCellElem(cellElem);
        }
    }

    protected final Sheet getSheet() {
        return this.parent;
    }

    private void addCellElem(final Element cellElem) {
        final Cell cell = new Cell(this, cellElem);
        this.cells.add(cell);

        final String repeatedS = cellElem.getAttributeValue("number-columns-repeated", this.getSheet().getTABLE());
        if (repeatedS != null) {
            final int toRepeat = Integer.parseInt(repeatedS) - 1;
            for (int i = 0; i < toRepeat; i++) {
                this.cells.add(cell);
            }
        }
    }

    /**
     * All cells of this row.
     * 
     * @return cells of this row, only "table-cell" and "covered-table-cell".
     */
    @SuppressWarnings("unchecked")
    private List<Element> getCellElements() {
        // seuls table-cell et covered-table-cell sont légaux
        return this.getElement().getChildren();
    }

    protected final Cell getCellAt(int col) {
        return this.cells.get(col);
    }

    protected final Cell getValidCellAt(int col) {
        final Cell c = this.getCellAt(col);
        if (!c.isValid())
            throw new IllegalArgumentException("invalid cell " + c);
        return c;
    }

    public final MutableCell getMutableCellAt(final int col) {
        final Cell c = this.getValidCellAt(col);
        if (!(c instanceof MutableCell)) {
            final Element element = c.getElement();
            final String repeatedS = element.getAttributeValue("number-columns-repeated", this.getSheet().getTABLE());
            if (repeatedS != null) {
                final int repeated = Integer.parseInt(repeatedS);
                final int firstIndex = this.cells.indexOf(c);
                final int lastIndex = firstIndex + repeated - 1;

                final int preRepeated = col - firstIndex;
                final int postRepeated = lastIndex - col;

                casse(element, firstIndex, preRepeated, true);
                element.removeAttribute("number-columns-repeated", this.getSheet().getTABLE());
                casse(element, col + 1, postRepeated, false);
            }
            this.cells.set(col, new MutableCell(this, element));
        }
        return (MutableCell) this.getValidCellAt(col);
    }

    private final void casse(Element element, int firstIndex, int repeat, boolean before) {
        if (repeat > 0) {
            final Element newElem = (Element) element.clone();
            element.getParentElement().addContent(element.getParent().indexOf(element) + (before ? 0 : 1), newElem);
            newElem.setAttribute("number-columns-repeated", repeat + "", this.getSheet().getTABLE());
            final Cell preCell = new Cell(this, newElem);
            for (int i = 0; i < repeat; i++) {
                this.cells.set(firstIndex + i, preCell);
            }
        }
    }

    // rempli cette ligne avec autant de cellules vides qu'il faut
    void columnCountChanged() {
        final int diff = this.getSheet().getColumnCount() - this.cells.size();
        if (diff < 0) {
            CollectionUtils.delete(this.cells, this.getSheet().getColumnCount());
        } else if (diff > 0) {
            final Element e = Cell.createEmpty(this.getSheet().getSpreadSheet().getNS(), diff);
            this.getElement().addContent(e);
            addCellElem(e);
        }
        if (this.cells.size() != this.getSheet().getColumnCount())
            throw new IllegalStateException();
    }
}
