/* 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.storage.directory.StorageDirectory;
import fr.exemole.bdfserver.storage.directory.bdfdata.BdfdataStorageFileCatalog;
import fr.exemole.bdfserver.storage.directory.bdfdata.Remove;
import fr.exemole.bdfserver.storage.directory.bdfdata.Save;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import net.fichotheque.EditOrigin;
import net.fichotheque.junction.JunctionKey;
import net.fichotheque.junction.JunctionRevision;
import net.fichotheque.tools.dom.revisions.JunctionRevisionDOMReader;
import org.w3c.dom.Document;
import net.fichotheque.junction.Junction;
import net.fichotheque.impl.JunctionDataSource;


/**
 *
 * @author Vincent Calame
 */
public class JunctionDataSourceImpl implements JunctionDataSource {

    private final StorageDirectory bdfdataDirectory;

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

    @Override
    public void saveJunction(Junction junction, EditOrigin editOrigin) {
        if (editOrigin == null) {
            throw new IllegalArgumentException("editOrigin is null");
        }
        Save.saveJunction(bdfdataDirectory, junction, editOrigin);
    }

    @Override
    public void removeJunction(JunctionKey junctionKey, EditOrigin editOrigin) {
        if (editOrigin == null) {
            throw new IllegalArgumentException("editOrigin is null");
        }
        Remove.removeJunction(bdfdataDirectory, junctionKey, editOrigin);
    }

    @Override
    public JunctionRevision getJunctionRevision(JunctionKey junctionKey, String revisionName) {
        StorageFile storageFile = BdfdataStorageFileCatalog.junction(bdfdataDirectory, junctionKey);
        Document document = storageFile.readDocument(revisionName);
        if (document == null) {
            return null;
        }
        JunctionRevisionDOMReader junctionRevisionDOMReader = new JunctionRevisionDOMReader();
        return junctionRevisionDOMReader.readJunctionRevision(document.getDocumentElement());
    }

}
