/* BdfServer_Multi - Copyright (c) 2022-2023 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.multi.htmlproducers;

import fr.exemole.bdfserver.html.AppInit;
import fr.exemole.bdfserver.multi.api.Multi;
import fr.exemole.bdfserver.multi.api.central.CentralUser;
import fr.exemole.bdfserver.multi.json.CentralUserJson;
import fr.exemole.bdfserver.tools.apps.AppConf;
import fr.exemole.bdfserver.tools.storage.StorageUtils;
import net.mapeadores.util.html.JsObject;
import net.mapeadores.util.html.TrustedHtml;
import net.mapeadores.util.html.jsoup.HtmlCleaners;
import net.mapeadores.util.io.DocStream;
import net.mapeadores.util.text.RelativePath;


/**
 *
 * @author Vincent Calame
 */
public class AppHtmlProducer extends MultiHtmlProducer {

    private final AppConf appConf;
    private final CentralUser centralUser;

    public AppHtmlProducer(Multi multi, AppConf appConf) {
        super(multi, multi.getMultiMetadata().getWorkingLangs().get(0));
        this.appConf = appConf;
        this.centralUser = null;
        AppInit.init(this, appConf, multi.getWebappsResourceStorages(), null);
    }

    public AppHtmlProducer(Multi multi, AppConf appConf, CentralUser centralUser) {
        super(multi, centralUser.getUserLangContext().getLangPreference());
        this.appConf = appConf;
        this.centralUser = centralUser;
        AppInit.init(this, appConf, multi.getWebappsResourceStorages(), null);
    }

    @Override
    public void printHtml() {
        start(getTitle(appConf.getAppName()));
        RelativePath appHtmlPath = StorageUtils.buildAppResourcePath(appConf.getAppName(), "app.html");
        DocStream docStream = multi.getWebappsResourceStorages().getResourceDocStream(appHtmlPath);
        if (docStream != null) {
            String appHtml = docStream.getContent();
            TrustedHtml trustedHtml = HtmlCleaners.WELLFORMED.cleanHtml(appHtml);
            this
                    .__append(trustedHtml);
        }
        JsObject jsObject = appConf.getArgsJsObject();
        if (jsObject != null) {
            this
                    .SCRIPT()
                    .__jsObject("ARGS", jsObject)
                    ._SCRIPT();
        }
        if (centralUser != null) {
            JsObject centralUserJsObject = new JsObject();
            CentralUserJson.populate(centralUserJsObject, centralUser);
            this
                    .SCRIPT()
                    .__jsObject("CENTRALUSER", centralUserJsObject)
                    .__jsObject("BDFUSER", centralUserJsObject)
                    ._SCRIPT();
        }
        end();
    }

}
