/* FichothequeLib_Tools - Copyright (c) 2016-2023 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.fichotheque.tools.exportation.table;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.fichotheque.SubsetKey;
import net.fichotheque.exportation.table.ColDef;
import net.mapeadores.opendocument.io.OdXML;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
public class NamedRangeHandler {

    private final static int MAX = 26 * 27;
    private SubsetKey currentSubsetKey;
    private String tableName;
    private final List<NamedRange> namedRangeList = new ArrayList<NamedRange>();

    public NamedRangeHandler() {

    }

    public void setCurrentTableName(String tableName) {
        this.tableName = tableName;
    }

    public void setCurrentSubset(SubsetKey subsetKey) {
        this.currentSubsetKey = subsetKey;
    }

    public void addColumnSum(int rowNumber, int colIndex, ColDef colDef) {
        if (colIndex >= MAX) {
            return;
        }
        String name = "columnsum_" + currentSubsetKey + "_" + colDef.getColName();
        StringBuilder addressBuf = new StringBuilder();
        addressBuf.append("$'");
        int length = tableName.length();
        for (int i = 0; i < length; i++) {
            char carac = tableName.charAt(i);
            if (carac == '\'') {
                addressBuf.append("''");
            } else {
                addressBuf.append(carac);
            }
        }
        addressBuf.append("'.$");
        addressBuf.append(OdXML.toLetter(colIndex + 1));
        addressBuf.append("$");
        addressBuf.append(rowNumber);
        namedRangeList.add(new NamedRange(name, addressBuf.toString()));
    }

    public void toXML(XMLWriter xmlWriter) throws IOException {
        if (namedRangeList.isEmpty()) {
            return;
        }
        OdXML.openNamedExpressions(xmlWriter);
        for (NamedRange namedRange : namedRangeList) {
            namedRange.toXML(xmlWriter);
        }
        OdXML.closeNamedExpressions(xmlWriter);
    }


    private static class NamedRange {

        private final String name;
        private final String address;

        private NamedRange(String name, String address) {
            this.name = name;
            this.address = address;
        }

        private void toXML(XMLWriter xmlWriter) throws IOException {
            OdXML.addNamedRange(xmlWriter, name, address);
        }

    }


}
