/* BdfServer_DirectoryStorage - Copyright (c) 2014-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 fr.exemole.bdfserver.storage.directory.implementations;

import fr.exemole.bdfserver.api.policies.UserAllow;
import fr.exemole.bdfserver.api.storage.BdfStorageException;
import fr.exemole.bdfserver.api.storage.PolicyStorage;
import fr.exemole.bdfserver.storage.directory.StorageDirectory;
import fr.exemole.bdfserver.storage.directory.bdfdata.BdfdataConstants;
import fr.exemole.bdfserver.tools.policies.UserAllowBuilder;
import fr.exemole.bdfserver.tools.policies.dom.ThesaurusPolicyDOMReader;
import fr.exemole.bdfserver.tools.policies.dom.UserAllowDOMReader;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import fr.exemole.bdfserver.xml.policies.ThesaurusPolicyXMLPart;
import fr.exemole.bdfserver.xml.policies.UserAllowXMLPart;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import net.fichotheque.Fichotheque;
import net.fichotheque.SubsetKey;
import net.fichotheque.thesaurus.policies.DynamicEditPolicy;
import net.mapeadores.util.logging.MultiMessageHandler;
import net.mapeadores.util.xml.AppendableXMLWriter;
import net.mapeadores.util.xml.XMLUtils;
import org.w3c.dom.Document;


/**
 *
 * @author Vincent Calame
 */
public class PolicyStorageImpl implements PolicyStorage {

    private final StorageDirectory bdfdataDirectory;
    private final String rootPath = BdfdataConstants.CONF + File.separator + "policies";

    public PolicyStorageImpl(StorageDirectory bdfdataDirectory) {
        this.bdfdataDirectory = bdfdataDirectory;
    }

    @Override
    public void saveUserAllow(UserAllow userAllow) {
        StorageFile storageFile = getUserAllowFile();
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            UserAllowXMLPart xmlPart = new UserAllowXMLPart(xmlWriter);
            xmlPart.addUserAllow(userAllow);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

    @Override
    public void saveSubsetPolicy(SubsetKey subsetKey, Object policyObject) {
        if ((!subsetKey.isThesaurusSubset()) || (policyObject == null)) {
            removeSubsetPolicy(subsetKey);
            return;
        }
        if (!(policyObject instanceof DynamicEditPolicy)) {
            throw new IllegalArgumentException("policyObject is not instance of DynamicEditPolicy");
        }
        StorageFile storageFile = getSubsetPolicyFile(subsetKey);
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            ThesaurusPolicyXMLPart thesaurusPolicyXMLPart = new ThesaurusPolicyXMLPart(xmlWriter);
            thesaurusPolicyXMLPart.addThesaurusPolicy(subsetKey, (DynamicEditPolicy) policyObject);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

    @Override
    public void removeSubsetPolicy(SubsetKey subsetKey) {
        StorageFile storageFile = getSubsetPolicyFile(subsetKey);
        if (storageFile.exists()) {
            storageFile.delete();
        }
    }

    public UserAllow checkUserAllow(MultiMessageHandler messageHandler) {
        UserAllowBuilder builder = new UserAllowBuilder();
        StorageFile storageFile = getUserAllowFile();
        if (storageFile.exists()) {
            messageHandler.setCurrentSource(storageFile.toURI());
            Document doc = storageFile.readDocument();
            UserAllowDOMReader userAllowDOMReader = new UserAllowDOMReader(builder, messageHandler);
            userAllowDOMReader.readUserAllow(doc.getDocumentElement());
        }
        return builder.toUserAllow();
    }

    public Map<SubsetKey, Object> checkSubsetPolicyMap(MultiMessageHandler messageHandler, Fichotheque fichotheque) {
        Map<SubsetKey, Object> result = new HashMap<SubsetKey, Object>();
        File treesDirectory = bdfdataDirectory.getDataDir(rootPath);
        if (!treesDirectory.exists()) {
            return result;
        }
        ThesaurusPolicyDOMReader domReader = new ThesaurusPolicyDOMReader(messageHandler, fichotheque);
        for (File f : treesDirectory.listFiles()) {
            if (f.isDirectory()) {
                continue;
            }
            String fileName = f.getName();
            if (fileName.endsWith(".xml")) {
                try {
                    SubsetKey subsetKey = SubsetKey.parse(fileName.substring(0, fileName.length() - 4));
                    if (subsetKey.isThesaurusSubset()) {
                        StorageFile storageFile = bdfdataDirectory.getStorageFile(rootPath + File.separator + fileName);
                        messageHandler.setCurrentSource(storageFile.toURI());
                        Document doc = storageFile.readDocument();
                        DynamicEditPolicy policy = domReader.readDynamicEditPolicy(doc.getDocumentElement(), subsetKey);
                        if (policy != null) {
                            result.put(subsetKey, policy);
                        }
                    }
                } catch (ParseException pe) {
                }
            }
        }
        return result;
    }

    private StorageFile getUserAllowFile() {
        return bdfdataDirectory.getStorageFile(rootPath + File.separator + "user-allow.xml");
    }

    private StorageFile getSubsetPolicyFile(SubsetKey subsetKey) {
        return bdfdataDirectory.getStorageFile(rootPath + File.separator + subsetKey + ".xml");
    }

}
