/*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.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;
import net.fichotheque.junction.Junction;


/**
 *
 * @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());
        Junction junction = illustrationExtractInfo.getJunction();
        if (tagName != null) {
            startOpenTag(tagName);
            addAttribute("album", illustration.getSubsetName());
            addAttribute("id", illustration.getId());
            addAttribute("format", illustration.getFormatType());
            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(junction);
            if (weight > 0) {
                addAttribute(tagNames.getWeightAttributeName(), weight);
            }
            if (junction == null) {
                closeEmptyTag();
            } else {
                endOpenTag();
                ExtractionXMLUtils.writeJunction(this, junction, 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";
        }
    }

}
