/* FichothequeLib_Xml - 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 net.fichotheque.xml.importation;

import java.io.IOException;
import java.util.List;
import net.fichotheque.importation.TiesImport;
import net.fichotheque.include.IncludeKey;
import net.mapeadores.util.text.Label;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
public class TiesImportXMLPart extends XMLPart {

    public TiesImportXMLPart(XMLWriter xmlWriter) {
        super(xmlWriter);
    }

    public void addTiesImport(TiesImport tiesImport) throws IOException {
        List<IncludeKey> removedIncludeKeyList = tiesImport.getRemovedIncludeKeyList();
        if (!removedIncludeKeyList.isEmpty()) {
            startOpenTag("ties");
            addAttribute("type", "remove");
            endOpenTag();
            for (IncludeKey includeKey : removedIncludeKeyList) {
                addSimpleElement("include-key", includeKey.getKeyString());
            }
            closeTag("ties");
        }
        List<TiesImport.TieImport> replaceList = tiesImport.getReplaceTieImportList();
        if (!replaceList.isEmpty()) {
            startOpenTag("ties");
            addAttribute("type", "replace");
            endOpenTag();
            for (TiesImport.TieImport tieImport : replaceList) {
                addTieImport(tieImport);
            }
            closeTag("ties");
        }
        List<TiesImport.TieImport> appendList = tiesImport.getAppendTieImportList();
        if (!appendList.isEmpty()) {
            startOpenTag("ties");
            addAttribute("type", "append");
            endOpenTag();
            for (TiesImport.TieImport tieImport : appendList) {
                addTieImport(tieImport);
            }
            closeTag("ties");
        }
    }

    private void addTieImport(TiesImport.TieImport tieImport) throws IOException {
        startOpenTag("tie");
        addAttribute("include-key", tieImport.getIncludeKey().getKeyString());
        addAttribute("weight", tieImport.getWeight());
        TiesImport.Other other = tieImport.getOther();
        if (other instanceof TiesImport.IdOther) {
            addAttribute("id", ((TiesImport.IdOther) other).getOtherId());
        } else if (other instanceof TiesImport.LabelOther) {
            Label label = ((TiesImport.LabelOther) other).getLabel();
            addAttribute("lang", label.getLang().toString());
            addAttribute("label", label.getLabelString());
        } else if (other instanceof TiesImport.IdalphaOther) {
            addAttribute("idalpha", ((TiesImport.IdalphaOther) other).getIdalpha());
        }
        closeEmptyTag();
    }

}
