/*FichothequeLib_Xml - Copyright (c) 2011-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.extraction;

import java.io.IOException;
import net.fichotheque.album.Illustration;
import net.fichotheque.croisement.Croisement;
import net.fichotheque.extraction.ExtractParameters;
import net.fichotheque.extraction.def.IllustrationFilter;
import net.fichotheque.extraction.def.TagNameInfo;
import net.fichotheque.extraction.run.IllustrationExtractInfo;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLWriter;


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

    private final ExtractParameters extractParameters;
    private final TagNames tagNames;

    public IllustrationXMLPart(XMLWriter xmlWriter, ExtractParameters extractParameters) {
        super(xmlWriter);
        this.extractParameters = extractParameters;
        this.tagNames = new TagNames(extractParameters.getExtractVersion());
    }

    public void addIllustration(IllustrationExtractInfo illustrationExtractInfo) throws IOException {
        IllustrationFilter illustrationFilter = illustrationExtractInfo.getIllustrationFilter();
        Illustration illustration = illustrationExtractInfo.getIllustration();
        String tagName = getTagName(illustrationFilter.getTagNameInfo());
        Croisement croisement = illustrationExtractInfo.getCroisement();
        if (tagName != null) {
            startOpenTag(tagName);
            addAttribute("album", illustration.getSubsetName());
            addAttribute("id", illustration.getId());
            addAttribute("format", illustration.getFormatTypeString());
            int width = illustration.getOriginalWidth();
            int height = illustration.getOriginalHeight();
            addAttribute("width", width);
            addAttribute("height", height);
            addAttribute("ratio", String.valueOf(((float) width) / height));
            int weight = ExtractionXMLUtils.getMainWeight(croisement);
            if (weight > 0) {
                addAttribute(tagNames.getWeightAttributeName(), weight);
            }
            if (croisement == null) {
                closeEmptyTag();
            } else {
                endOpenTag();
                ExtractionXMLUtils.writeCroisement(this, croisement, tagNames);
                closeTag(tagName);
            }
        }
    }

    private String getTagName(TagNameInfo tagNameInfo) {
        switch (tagNameInfo.getType()) {
            case TagNameInfo.CUSTOM_TYPE:
                return tagNameInfo.getCustomTagName();
            case TagNameInfo.NULL_TYPE:
                return null;
            default:
                return "illustration";
        }
    }

}
