/* BdfServer - Copyright (c) 2024 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.xml.dyn;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.configuration.ConfigurationUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLWriter;


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

    private final static Map<String, String> DEFAULT_MAP = new HashMap<String, String>();
    private final BdfServer bdfServer;

    static {
        DEFAULT_MAP.put("width", "3cm");
        DEFAULT_MAP.put("height", "3cm");
        DEFAULT_MAP.put("anchor", "as-char");
        DEFAULT_MAP.put("style", "FicheLogo");
    }

    public LogoResourceXMLPart(XMLWriter xmlWriter, BdfServer bdfServer) {
        super(xmlWriter);
        this.bdfServer = bdfServer;
    }

    public void appendForDestination(String destination) throws IOException {
        startOpenTag("resource");
        addAttribute("type", "image");
        switch (destination) {
            case "odt":
                appendOdtLogo();
                break;
            default:
                endOpenTag();
        }
        closeTag("resource");
    }

    private void appendOdtLogo() throws IOException {
        Map<String, String> logoMap = ConfigurationUtils.getOdtLogoParameters(bdfServer);
        if (!logoMap.containsKey("path")) {
            endOpenTag();
            return;
        }
        addAttribute("path", logoMap.get("path"));
        endOpenTag();
        for (Map.Entry<String, String> entry : logoMap.entrySet()) {
            String key = entry.getKey();
            if (!key.equals("path")) {
                addParam(key, entry.getValue());
            }
        }
        checkDefault(logoMap);
    }

    private void checkDefault(Map<String, String> map) throws IOException {
        for (Map.Entry<String, String> entry : DEFAULT_MAP.entrySet()) {
            String key = entry.getKey();
            if (!map.containsKey(key)) {
                addParam(key, entry.getValue());
            }
        }
    }

    private void addParam(String name, String value) throws IOException {
        startOpenTag("param");
        addAttribute("name", name);
        endOpenTag();
        addText(value);
        closeTag("param", false);
    }

}
