/* 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.groups.GroupDef;
import fr.exemole.bdfserver.api.storage.BdfStorageException;
import fr.exemole.bdfserver.api.storage.GroupStorage;
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.groups.GroupDefBuilder;
import fr.exemole.bdfserver.tools.groups.dom.GroupDefDOMReader;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import fr.exemole.bdfserver.xml.groups.GroupDefXMLPart;
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.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 GroupStorageImpl implements GroupStorage {

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

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

    public List<GroupDef> check(MultiMessageHandler messageHandler) {
        List<GroupDef> result = new ArrayList<GroupDef>();
        File groupDirectory = bdfdataDirectory.getDataDir(rootPath);
        if (!groupDirectory.exists()) {
            return result;
        }
        File[] fileList = groupDirectory.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")) {
                String groupName = fileName.substring(0, fileName.length() - 4);
                try {
                    GroupDef.checkGroupName(groupName);
                    GroupDefBuilder groupDefBuilder = GroupDefBuilder.init(groupName);
                    StorageFile storageFile = bdfdataDirectory.getStorageFile(rootPath + File.separator + fileName);
                    messageHandler.setCurrentSource(storageFile.toURI());
                    Document doc = storageFile.readDocument();
                    GroupDefDOMReader.init(groupDefBuilder, messageHandler)
                            .read(doc.getDocumentElement());
                    result.add(groupDefBuilder.toGroupDef());
                } catch (ParseException pe) {
                    messageHandler.setCurrentSource(f.getPath());
                    messageHandler.addMessage(StorageFactory.SEVERE_FILENAME, "_ error.wrong.filename", groupName);
                }
            }
        }
        return result;
    }

    @Override
    public void saveGroupDef(GroupDef groupDef) {
        StorageFile storageFile = getGroupFile(groupDef.getName());
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            GroupDefXMLPart xmlPart = new GroupDefXMLPart(xmlWriter);
            xmlPart.addGroupDef(groupDef);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

    @Override
    public void removeGroupDef(String groupName) {
        StorageFile storageFile = getGroupFile(groupName);
        storageFile.delete();
    }

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

}
