/* BdfServer_DirectoryStorage - Copyright (c) 2013-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.roles.RoleDef;
import fr.exemole.bdfserver.api.storage.BdfStorageException;
import fr.exemole.bdfserver.api.storage.RoleStorage;
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.roles.RoleDefBuilder;
import fr.exemole.bdfserver.tools.roles.dom.RoleDefDOMReader;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import fr.exemole.bdfserver.xml.roles.RoleDefXMLPart;
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 RoleStorageImpl implements RoleStorage {

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

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

    public List<RoleDef> check(MultiMessageHandler messageHandler) {
        List<RoleDef> result = new ArrayList<RoleDef>();
        File roleDirectory = bdfdataDirectory.getDataDir(rootPath);
        if (!roleDirectory.exists()) {
            return result;
        }
        File[] fileList = roleDirectory.listFiles();
        int length = fileList.length;
        for (int i = 0; i < length; i++) {
            File f = fileList[i];
            String fileName = f.getName();
            if (fileName.endsWith(".xml")) {
                String roleName = fileName.substring(0, fileName.length() - 4);
                try {
                    RoleDef.checkRoleName(roleName);
                    RoleDefBuilder roleDefBuilder = RoleDefBuilder.init(roleName);
                    StorageFile storageFile = bdfdataDirectory.getStorageFile(rootPath + File.separator + fileName);
                    messageHandler.setCurrentSource(storageFile.toURI());
                    Document doc = storageFile.readDocument();
                    RoleDefDOMReader.init(roleDefBuilder, messageHandler)
                            .read(doc.getDocumentElement());
                    result.add(roleDefBuilder.toRoleDef());
                } catch (ParseException pe) {
                    messageHandler.setCurrentSource(f.getPath());
                    messageHandler.addMessage(StorageFactory.SEVERE_FILENAME, "_ error.wrong.filename", roleName);
                }
            }
        }
        return result;
    }

    @Override
    public void saveRoleDef(RoleDef roleDef) {
        StorageFile storageFile = getRoleFile(roleDef.getName());
        try (BufferedWriter buf = storageFile.getWriter()) {
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            RoleDefXMLPart xmlPart = new RoleDefXMLPart(xmlWriter);
            xmlPart.addRoleDef(roleDef);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

    @Override
    public void removeRoleDef(String roleName) {
        StorageFile storageFile = getRoleFile(roleName);
        storageFile.delete();
    }

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

}
