/* BdfServer - Copyright (c) 2013-2025 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 fr.exemole.bdfserver.tools.ficheform.builders;

import fr.exemole.bdfserver.api.ficheform.AmountInfoSubfieldsElement;
import fr.exemole.bdfserver.api.ficheform.FicheFormParameters;
import fr.exemole.bdfserver.api.ui.FieldUi;
import fr.exemole.bdfserver.tools.L10nUtils;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
import net.fichotheque.corpus.fiche.AmountItem;
import net.fichotheque.corpus.fiche.FicheItem;
import net.fichotheque.corpus.fiche.FicheItems;
import net.fichotheque.corpus.metadata.CorpusField;
import net.fichotheque.pointeurs.FichePointeur;
import net.fichotheque.syntax.FormSyntax;
import net.fichotheque.utils.FicheUtils;
import net.mapeadores.util.attr.AttributeUtils;
import net.mapeadores.util.attr.Attributes;
import net.mapeadores.util.money.Currencies;
import net.mapeadores.util.money.ExtendedCurrency;
import net.mapeadores.util.text.SeparatorOptions;


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

    private final CorpusField corpusField;
    private final Map<ExtendedCurrency, String> currencyMap = new LinkedHashMap<ExtendedCurrency, String>();
    private String label = "";
    private boolean mandatory = false;
    private String othersValue = "";
    private Attributes attributes = AttributeUtils.EMPTY_ATTRIBUTES;

    public AmountInfoSubfieldsElementBuilder(CorpusField corpusField) {
        this.corpusField = corpusField;
        Currencies currencies = corpusField.getCurrencies();
        if (currencies == null) {
            throw new IllegalArgumentException("corpusField.getFieldOptions().getCurrencies() is null");
        }
        for (ExtendedCurrency currency : currencies) {
            currencyMap.put(currency, "");
        }
    }

    public AmountInfoSubfieldsElementBuilder setLabel(String label) {
        if (label == null) {
            throw new IllegalArgumentException("label is null");
        }
        this.label = label;
        return this;
    }

    public AmountInfoSubfieldsElementBuilder setMandatory(boolean mandatory) {
        this.mandatory = mandatory;
        return this;
    }

    public AmountInfoSubfieldsElementBuilder setAttributes(Attributes attributes) {
        if (attributes == null) {
            this.attributes = AttributeUtils.EMPTY_ATTRIBUTES;
        } else {
            this.attributes = attributes;
        }
        return this;
    }

    public AmountInfoSubfieldsElementBuilder putCurrency(ExtendedCurrency currency, String amountValue) {
        if (amountValue == null) {
            throw new IllegalArgumentException("amountValue is null");
        }
        if (currencyMap.containsKey(currency)) {
            currencyMap.put(currency, amountValue);
        }
        return this;
    }

    public AmountInfoSubfieldsElementBuilder setOthersValue(String othersValue) {
        if (othersValue == null) {
            throw new IllegalArgumentException("othersValue is null");
        }
        this.othersValue = othersValue;
        return this;
    }

    private AmountInfoSubfieldsElementBuilder setCurrencyFromFicheItems(FicheItems ficheItems, FicheFormParameters ficheFormParameters) {
        if (ficheItems == null) {
            return this;
        }
        FormSyntax.Parameters syntaxParameters = ficheFormParameters.getFicheItemFormSyntaxParameters();
        List<FicheItem> othersList = new ArrayList<FicheItem>();
        char decimalChar = syntaxParameters.decimalChar();
        for (FicheItem ficheItem : ficheItems) {
            if (ficheItem instanceof AmountItem) {
                AmountItem amountItem = (AmountItem) ficheItem;
                if (!currencyMap.containsKey(amountItem.getCurrency())) {
                    othersList.add(amountItem);
                } else {
                    currencyMap.put(amountItem.getCurrency(), amountItem.getDecimal().toStringWithBlank(decimalChar));
                }
            } else {
                othersList.add(ficheItem);
            }
        }
        if (!othersList.isEmpty()) {
            boolean isBlock = corpusField.isBlockDisplayInfoField();
            SeparatorOptions separatorOptions = (isBlock) ? ficheFormParameters.getBlockSeparatorOptions() : ficheFormParameters.getInlineSeparatorOptions();
            setOthersValue(FormSyntax.toString(FicheUtils.toFicheItems(othersList), ficheFormParameters.getBdfServer().getFichotheque(), separatorOptions, syntaxParameters));
        }
        return this;
    }

    public AmountInfoSubfieldsElement toAmountInfoSubfieldsElement() {
        int size = currencyMap.size();
        InternalEntry[] entryArray = new InternalEntry[size];
        int p = 0;
        for (Map.Entry<ExtendedCurrency, String> entry : currencyMap.entrySet()) {
            entryArray[p] = new InternalEntry(entry.getKey(), entry.getValue());
            p++;
        }
        return new InternalAmountInfoSubfieldsElement(corpusField, label, mandatory, attributes, wrap(entryArray), othersValue);
    }

    public static AmountInfoSubfieldsElementBuilder check(FichePointeur fichePointeur, FicheFormParameters ficheFormParameters, CorpusField corpusField, FieldUi fieldUi) {
        FicheItems ficheItems = (FicheItems) fichePointeur.getValue(corpusField);
        if ((ficheItems == null) && (fieldUi.isObsolete())) {
            return null;
        }
        return init(corpusField)
                .setCurrencyFromFicheItems(ficheItems, ficheFormParameters)
                .setAttributes(fieldUi.getAttributes())
                .setLabel(L10nUtils.toLabelString(ficheFormParameters, corpusField));
    }


    public static AmountInfoSubfieldsElementBuilder init(CorpusField corpusField) {
        return new AmountInfoSubfieldsElementBuilder(corpusField);
    }

    private static List<AmountInfoSubfieldsElement.Entry> wrap(AmountInfoSubfieldsElement.Entry[] array) {
        return new EntryList(array);
    }


    private static class InternalAmountInfoSubfieldsElement implements AmountInfoSubfieldsElement {

        private final CorpusField corpusField;
        private final String label;
        private final boolean mandatory;
        private final Attributes attributes;
        private final List<AmountInfoSubfieldsElement.Entry> entryList;
        private final String othersValue;

        private InternalAmountInfoSubfieldsElement(CorpusField corpusField, String label, boolean mandatory, Attributes attributes, List<AmountInfoSubfieldsElement.Entry> entryList, String othersValue) {
            this.corpusField = corpusField;
            this.label = label;
            this.mandatory = mandatory;
            this.attributes = attributes;
            this.entryList = entryList;
            this.othersValue = othersValue;
        }

        @Override
        public CorpusField getCorpusField() {
            return corpusField;
        }

        @Override
        public String getLabel() {
            return label;
        }

        @Override
        public boolean isMandatory() {
            return mandatory;
        }

        @Override
        public Attributes getAttributes() {
            return attributes;
        }

        @Override
        public List<AmountInfoSubfieldsElement.Entry> getEntryList() {
            return entryList;
        }

        @Override
        public String getOthersValue() {
            return othersValue;
        }

    }


    private static class InternalEntry implements AmountInfoSubfieldsElement.Entry {

        private final ExtendedCurrency currency;
        private final String value;

        private InternalEntry(ExtendedCurrency currency, String value) {
            this.currency = currency;
            this.value = value;
        }

        @Override
        public ExtendedCurrency getCurrency() {
            return currency;
        }

        @Override
        public String getAmountValue() {
            return value;
        }

    }


    private static class EntryList extends AbstractList<AmountInfoSubfieldsElement.Entry> implements RandomAccess {

        private final AmountInfoSubfieldsElement.Entry[] array;

        private EntryList(AmountInfoSubfieldsElement.Entry[] array) {
            this.array = array;
        }

        @Override
        public int size() {
            return array.length;
        }

        @Override
        public AmountInfoSubfieldsElement.Entry get(int index) {
            return array[index];
        }

    }

}
