/* BdfServer_DirectoryStorage - Copyright (c) 2011-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.ScrutariExportStorage;
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.scrutari.ScrutariExportDef;
import net.fichotheque.metadata.FichothequeMetadata;
import net.fichotheque.tools.exportation.scrutari.ScrutariExportDefBuilder;
import net.fichotheque.tools.exportation.scrutari.dom.ScrutariExportDefDOMReader;
import net.fichotheque.xml.defs.ScrutariExportDefXMLPart;
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 ScrutariExportStorageImpl implements ScrutariExportStorage {

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

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

    public List<ScrutariExportDef> check(MultiMessageHandler messageHandler) {
        List<ScrutariExportDef> result = new ArrayList<ScrutariExportDef>();
        File scrutariExportDirectory = bdfdataDirectory.getDataDir(rootPath);
        if (!scrutariExportDirectory.exists()) {
            return result;
        }
        FichothequeMetadata fichothequeMetadata = fichotheque.getFichothequeMetadata();
        File[] fileList = scrutariExportDirectory.listFiles();
        for (File f : fileList) {
            String fileName = f.getName();
            if (fileName.endsWith(".xml")) {
                String exportName = fileName.substring(0, fileName.length() - 4);
                StorageFile storageFile = bdfdataDirectory.getStorageFile(rootPath + File.separator + fileName);
                messageHandler.setCurrentSource(storageFile.toURI());
                try {
                    ScrutariExportDef.checkScrutariExportName(exportName);
                    ScrutariExportDefBuilder builder = ScrutariExportDefBuilder.init(exportName, fichothequeMetadata.getAuthority(), fichothequeMetadata.getBaseName());
                    Document doc = storageFile.readDocument();
                    ScrutariExportDefDOMReader.init(fichotheque, builder, messageHandler)
                            .read(doc.getDocumentElement());
                    result.add(builder.toScrutariExportDef());
                } catch (ParseException pe) {
                    messageHandler.setCurrentSource(f.getPath());
                    messageHandler.addMessage(StorageFactory.SEVERE_FILENAME, "_ error.wrong.filename", fileName);
                }
            }
        }
        return result;
    }

    @Override
    public void saveScrutariExportDef(ScrutariExportDef scrutariExportDef) {
        StorageFile storageFile = getScrutariExportFile(scrutariExportDef.getName());
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            ScrutariExportDefXMLPart.init(xmlWriter)
                    .addScrutariExportDef(scrutariExportDef);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

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

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

}
