/* 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.BdfStorageException;
import fr.exemole.bdfserver.api.storage.SelectionStorage;
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.selection.SelectionDef;
import net.fichotheque.tools.selection.SelectionDefBuilder;
import net.fichotheque.tools.selection.dom.SelectionDefDOMReader;
import net.fichotheque.xml.defs.SelectionDefXMLPart;
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 SelectionStorageImpl implements SelectionStorage {

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

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

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

            }
        }
        return result;
    }

    @Override
    public void saveSelectionDef(SelectionDef selectionDef) {
        StorageFile storageFile = getSelectionFile(selectionDef.getName());
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            SelectionDefXMLPart.init(xmlWriter)
                    .addSelectionDef(selectionDef);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

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

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

}
