/* BdfServer - Copyright (c) 2022 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.exportation.transformation.compilers;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import net.fichotheque.album.Illustration;
import net.mapeadores.opendocument.transform.PictureHandler;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
class ImageXMLPart extends XMLPart {

    private final PictureHandler pictureHandler;
    private final Set<String> usedNameSet = new HashSet<String>();

    ImageXMLPart(XMLWriter xmlWriter, PictureHandler pictureHandler) {
        super(xmlWriter);
        this.pictureHandler = pictureHandler;
    }

    public void write(Illustration illustration, PropertyPart propertyPart) throws IOException {
        String href = pictureHandler.checkHref("bdf://this/illustrations/" + illustration.getSubsetName() + "-" + illustration.getId());
        FrameDim frameDim = FrameDim.build(illustration, propertyPart);
        String drawName = checkName(illustration.getGlobalId());
        startOpenTag("draw:frame");
        addAttribute("draw:name", drawName);
        addAttribute("draw:style-name", "FbeIllustration");
        addAttribute("text:anchor-type", "as-char");
        addAttribute("svg:width", frameDim.getWidth());
        addAttribute("svg:height", frameDim.getHeight());
        addAttribute("draw:z-index", "0");
        endOpenTag();
        startOpenTag("draw:image");
        addAttribute("xlink:href", href);
        addAttribute("xlink:type", "simple");
        addAttribute("xlink:show", "embed");
        addAttribute("xlink:actuate", "onLoad");
        closeEmptyTag();
        closeTag("draw:frame");
    }

    private String checkName(String name) {
        if (!usedNameSet.contains(name)) {
            usedNameSet.add(name);
            return name;
        }
        int suppNumber = 2;
        String newName;
        while (true) {
            newName = name + "_" + suppNumber;
            if (!usedNameSet.contains(newName)) {
                break;
            }
            suppNumber++;
        }
        usedNameSet.add(newName);
        return newName;
    }

}
