/* 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.SqlExportStorage;
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.sql.SqlExportDef;
import net.fichotheque.tools.exportation.sql.SqlExportDefBuilder;
import net.fichotheque.tools.exportation.sql.dom.SqlExportDefDOMReader;
import net.fichotheque.xml.defs.SqlExportDefXMLPart;
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 SqlExportStorageImpl implements SqlExportStorage {

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

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

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

            }
        }
        return result;
    }

    @Override
    public void saveSqlExportDef(SqlExportDef sqlExportDef) {
        StorageFile storageFile = getSqlExportFile(sqlExportDef.getName());
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            SqlExportDefXMLPart.init(xmlWriter)
                    .addSqlExportDef(sqlExportDef);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

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

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

}
