/* 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.storage.BdfStorageException;
import fr.exemole.bdfserver.api.storage.TreeStorage;
import fr.exemole.bdfserver.api.subsettree.SubsetTree;
import fr.exemole.bdfserver.storage.directory.StorageDirectory;
import fr.exemole.bdfserver.storage.directory.bdfdata.BdfdataConstants;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import fr.exemole.bdfserver.tools.subsettree.SubsetTreeBuilder;
import fr.exemole.bdfserver.tools.subsettree.dom.TreeDOMReader;
import fr.exemole.bdfserver.xml.subsettree.TreeXMLPart;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import net.fichotheque.SubsetKey;
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 TreeStorageImpl implements TreeStorage {

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

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

    @Override
    public void saveSubsetTree(short subsetCategory, SubsetTree subsetTree) {
        StorageFile storageFile = getTreeFile(subsetCategory);
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            TreeXMLPart xmlPart = new TreeXMLPart(xmlWriter);
            xmlPart.addTree(subsetTree);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

    public Map<Short, SubsetTree> check(MultiMessageHandler messageHandler) {
        Map<Short, SubsetTree> result = new HashMap<Short, SubsetTree>();
        File treesDirectory = bdfdataDirectory.getDataDir(rootPath);
        if (!treesDirectory.exists()) {
            return result;
        }
        File[] fileList = treesDirectory.listFiles();
        int length = fileList.length;
        for (int i = 0; i < length; i++) {
            File f = fileList[i];
            if (f.isDirectory()) {
                continue;
            }
            String fileName = f.getName();
            if (fileName.endsWith(".xml")) {
                try {
                    SubsetTreeBuilder subsetTreeBuilder = new SubsetTreeBuilder(true);
                    short category = SubsetKey.categoryToShort(fileName.substring(0, fileName.length() - 4));
                    StorageFile storageFile = bdfdataDirectory.getStorageFile(rootPath + File.separator + fileName);
                    messageHandler.setCurrentSource(storageFile.toURI());
                    Document doc = storageFile.readDocument();
                    TreeDOMReader treeDOMReader = new TreeDOMReader(subsetTreeBuilder, messageHandler);
                    treeDOMReader.readTree(doc.getDocumentElement());
                    result.put(category, subsetTreeBuilder.toSubsetTree());
                } catch (IllegalArgumentException iae) {
                }
            }
        }
        return result;
    }

    private StorageFile getTreeFile(short subsetCategory) {
        return bdfdataDirectory.getStorageFile(rootPath + File.separator + SubsetKey.categoryToString(subsetCategory) + ".xml");
    }

}
