/* BdfServer_HtmlProducers - Copyright (c) 2013-2021 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.htmlproducers.addenda;

import fr.exemole.bdfserver.api.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.domains.AddendaDomain;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.jslib.DocumentJsLibs;
import fr.exemole.bdfserver.tools.configuration.ConfigurationUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.addenda.Addenda;
import net.fichotheque.addenda.Document;
import net.fichotheque.addenda.Version;
import net.fichotheque.tools.parsers.DocumentChangeInfo;
import net.fichotheque.utils.FichothequeUtils;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.html.JsObject;
import net.mapeadores.util.text.FileName;


/**
 *
 * @author Vincent Calame
 */
public class DocumentChangeHtmlProducer extends BdfServerHtmlProducer {

    private final static String NOCHANGE_STATE = "nochange";
    private final static String UPDATE_STATE = "update";
    private final static String REMOVE_STATE = "remove";
    private final static String CREATE_STATE = "create";
    private final String appelant;
    private String originalName;
    private final String changeType;
    private String basename;
    private final List<VersionState> versionStateList = new ArrayList<VersionState>();
    private final Addenda addenda;
    private final String titleKey;
    private Document document;

    private DocumentChangeHtmlProducer(BdfParameters bdfParameters, String appelant, String changeType, Addenda addenda) {
        super(bdfParameters);
        addThemeCss("document.css");
        setBodyCssClass("global-body-ToolWindow");
        this.appelant = appelant;
        addJsLib(DocumentJsLibs.CHANGE);
        this.changeType = changeType;
        this.addenda = addenda;
        if (changeType.equals(AddendaDomain.DOCUMENT_CHANGETYPE)) {
            titleKey = "_ title.addenda.documentchange";
        } else if (changeType.equals(AddendaDomain.CREATION_CHANGETYPE)) {
            titleKey = "_ title.addenda.documentcreate";
        } else {
            titleKey = "";
        }
    }

    public static DocumentChangeHtmlProducer newDocumentCreate(BdfParameters bdfParameters, String appelant, String originalName, DocumentChangeInfo documentChangeInfo, Addenda addenda) {
        DocumentChangeHtmlProducer htmlProducer = new DocumentChangeHtmlProducer(bdfParameters, appelant, AddendaDomain.CREATION_CHANGETYPE, addenda);
        htmlProducer.originalName = originalName;
        htmlProducer.basename = documentChangeInfo.getNewBasename();
        int tmpFileNameCount = documentChangeInfo.getTmpFileCount();
        for (int i = 0; i < tmpFileNameCount; i++) {
            FileName tmpFileName = documentChangeInfo.getTmpFileName(i);
            VersionState versionState = new VersionState(tmpFileName.getExtension());
            versionState.state = CREATE_STATE;
            versionState.tmpFileName = tmpFileName;
            htmlProducer.versionStateList.add(versionState);
        }
        return htmlProducer;
    }

    public static DocumentChangeHtmlProducer newDocumentChange(BdfParameters bdfParameters, String appelant, Document document, DocumentChangeInfo documentChangeInfo, Addenda addenda) {
        DocumentChangeHtmlProducer htmlProducer = new DocumentChangeHtmlProducer(bdfParameters, appelant, AddendaDomain.DOCUMENT_CHANGETYPE, addenda);
        String currentBaseName = document.getBasename();
        String newBasename = documentChangeInfo.getNewBasename();
        if (newBasename != null) {
            htmlProducer.basename = newBasename;
        } else {
            htmlProducer.basename = currentBaseName;
        }
        htmlProducer.document = document;
        Map<String, FileName> changeMap = new LinkedHashMap<String, FileName>();
        int tmpFileNameCount = documentChangeInfo.getTmpFileCount();
        for (int i = 0; i < tmpFileNameCount; i++) {
            FileName tmpFileName = documentChangeInfo.getTmpFileName(i);
            changeMap.put(tmpFileName.getExtension(), tmpFileName);
        }
        Set<String> removedSet = new HashSet<String>();
        int removedExtensionCount = documentChangeInfo.getRemovedExtensionCount();
        for (int i = 0; i < removedExtensionCount; i++) {
            String extension = documentChangeInfo.getRemovedExtension(i);
            removedSet.add(extension);
            changeMap.remove(extension);
        }
        for (Version version : document.getVersionList()) {
            String extension = version.getExtension();
            VersionState versionState = new VersionState(extension);
            if (removedSet.contains(extension)) {
                versionState.state = REMOVE_STATE;
            } else if (changeMap.containsKey(extension)) {
                versionState.state = UPDATE_STATE;
                versionState.tmpFileName = changeMap.get(extension);
            } else {
                versionState.state = NOCHANGE_STATE;
            }
            versionState.currentFileName = currentBaseName + "." + extension;
            htmlProducer.versionStateList.add(versionState);
            changeMap.remove(extension);
        }
        for (Map.Entry<String, FileName> entry : changeMap.entrySet()) {
            String extension = entry.getKey();
            VersionState versionState = new VersionState(extension);
            versionState.state = CREATE_STATE;
            versionState.tmpFileName = entry.getValue();
            htmlProducer.versionStateList.add(versionState);
        }
        return htmlProducer;
    }

    @Override
    public void printHtml() {
        String clientId = generateId();
        JsObject args = JsObject.init()
                .put("clientId", clientId)
                .put("changeType", changeType)
                .put("appelant", appelant)
                .put("addenda", addenda.getSubsetName())
                .put("newName", basename)
                .put("originalName", originalName)
                .put("namingInfo", FichothequeUtils.getPhraseLabel(addenda.getMetadata().getPhrases(), FichothequeConstants.NAMING_PHRASE, workingLang));
        if (document != null) {
            args
                    .put("documentId", document.getId())
                    .put("documentName", document.getBasename());
        }
        List<JsObject> extensionList = new ArrayList<JsObject>();
        for (VersionState versionState : versionStateList) {
            String extension = versionState.getExtension();
            JsObject extensionObject = JsObject.init()
                    .put("extension", extension)
                    .put("state", versionState.getState());
            FileName tmpFileName = versionState.getTmpFileName();
            if (tmpFileName != null) {
                extensionObject
                        .put("tmpFileName", tmpFileName.toString())
                        .put("tmpUrl", ConfigurationUtils.getTmpRelativeUrl(tmpFileName.toString()));
            }
            String currentFileName = versionState.getCurrentFileName();
            if (currentFileName != null) {
                extensionObject
                        .put("currentFileName", currentFileName);
            }
            extensionList.add(extensionObject);
        }
        args.put("extensionArray", extensionList);
        startLoc(titleKey);
        this
                .SCRIPT()
                .__jsObject("AddendaDoc.Change.ARGS", args)
                ._SCRIPT();
        this
                .DIV(HA.id(clientId).classes("document-Client"))
                ._DIV();
        end();
    }


    private static class VersionState {

        private final String extension;
        private String state;
        private FileName tmpFileName;
        private String currentFileName;

        private VersionState(String extension) {
            this.extension = extension;
        }

        private String getExtension() {
            return extension;
        }

        private String getState() {
            return state;
        }

        private FileName getTmpFileName() {
            return tmpFileName;
        }

        private String getCurrentFileName() {
            return currentFileName;
        }

    }

}
