/* BdfServer_Multi - Copyright (c) 2023 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.multi.impl;

import fr.exemole.bdfserver.api.storage.BdfStorageException;
import fr.exemole.bdfserver.multi.xml.CentralSphereMetadataXMLPart;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import java.io.BufferedWriter;
import java.io.IOException;
import net.fichotheque.EditOrigin;
import net.fichotheque.utils.DefaultMetadata;
import net.fichotheque.utils.DefaultMetadataEditor;
import net.mapeadores.util.xml.AppendableXMLWriter;
import net.mapeadores.util.xml.XMLUtils;
import fr.exemole.bdfserver.storage.directory.StorageDirectory;


/**
 *
 * @author Vincent Calame
 */
class CentralSphereMetadataImpl extends DefaultMetadata {

    CentralSphereMetadataImpl() {

    }

    CentralSphereMetadataEditorImpl getSphereMetadataEditor(EditOrigin editOrigin) {
        return new CentralSphereMetadataEditorImpl(this, editOrigin);
    }


    static class CentralSphereMetadataEditorImpl extends DefaultMetadataEditor {

        private final CentralSphereMetadataImpl metadata;
        private final EditOrigin editOrigin;

        private CentralSphereMetadataEditorImpl(CentralSphereMetadataImpl metadata, EditOrigin editOrigin) {
            super(metadata);
            this.metadata = metadata;
            this.editOrigin = editOrigin;
        }

        boolean saveChanges(StorageDirectory storageDirectory, String name) {
            if (isWithChanges()) {
                StorageFile storageFile = MultiStorageFileCatalog.centralSphereMetadata(storageDirectory, name);
                try (BufferedWriter buf = storageFile.archiveAndGetWriter(editOrigin)) {
                    AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
                    xmlWriter.appendXMLDeclaration();
                    CentralSphereMetadataXMLPart part = new CentralSphereMetadataXMLPart(xmlWriter);
                    part.appendCentralSphereMetadata(metadata);
                } catch (IOException ioe) {
                    throw new BdfStorageException(ioe);
                }
                return true;
            } else {
                return false;
            }
        }

    }

}
