/* BdfServer_DirectoryStorage - Copyright (c) 2023-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.storage.AccessStorage;
import fr.exemole.bdfserver.api.storage.BdfStorageException;
import fr.exemole.bdfserver.storage.directory.StorageDirectory;
import fr.exemole.bdfserver.storage.directory.StorageFactory;
import fr.exemole.bdfserver.storage.directory.bdfdata.BdfdataConstants;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import net.fichotheque.Fichotheque;
import net.fichotheque.exportation.access.AccessDef;
import net.fichotheque.tools.exportation.access.AccessDefBuilder;
import net.fichotheque.tools.exportation.access.dom.AccessDefDOMReader;
import net.fichotheque.xml.defs.AccessDefXMLPart;
import net.mapeadores.util.logging.MultiMessageHandler;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.xml.AppendableXMLWriter;
import net.mapeadores.util.xml.XMLUtils;
import org.w3c.dom.Document;


/**
 *
 * @author Vincent Calame
 */
public class AccessStorageImpl implements AccessStorage {

    private final Fichotheque fichotheque;
    private final StorageDirectory bdfdataDirectory;
    private final String rootPath = BdfdataConstants.CONF + File.separator + "accesses";

    public AccessStorageImpl(Fichotheque fichotheque, StorageDirectory bdfdataDirectory) {
        this.fichotheque = fichotheque;
        this.bdfdataDirectory = bdfdataDirectory;
    }

    public List<AccessDef> check(MultiMessageHandler messageHandler) {
        List<AccessDef> result = new ArrayList<AccessDef>();
        File accessDirectory = bdfdataDirectory.getDataDir(rootPath);
        if (!accessDirectory.exists()) {
            return result;
        }
        for (File f : accessDirectory.listFiles()) {
            String fileName = f.getName();
            if (fileName.endsWith(".xml")) {
                String exportName = fileName.substring(0, fileName.length() - 4);
                try {
                    StringUtils.checkTechnicalName(exportName, true);
                    AccessDefBuilder builder = new AccessDefBuilder(exportName);
                    StorageFile storageFile = bdfdataDirectory.getStorageFile(rootPath + File.separator + fileName);
                    messageHandler.setCurrentSource(storageFile.toURI());
                    Document doc = storageFile.readDocument();
                    AccessDefDOMReader.init(fichotheque, builder, messageHandler)
                            .read(doc.getDocumentElement());
                    result.add(builder.toAccessDef());
                } catch (ParseException pe) {
                    messageHandler.addMessage(StorageFactory.SEVERE_FILENAME, "_ error.wrong.filename", fileName);
                }

            }
        }
        return result;
    }

    @Override
    public void saveAccessDef(AccessDef accessDef) {
        StorageFile storageFile = getAccessFile(accessDef.getName());
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            AccessDefXMLPart.init(xmlWriter)
                    .addAccessDef(accessDef);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

    @Override
    public void removeAccessDef(String name) {
        StorageFile storageFile = getAccessFile(name);
        storageFile.delete();
    }

    private StorageFile getAccessFile(String name) {
        return bdfdataDirectory.getStorageFile(rootPath + File.separator + name + ".xml");
    }

}
