package org.flexdock.perspective.persist;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.flexdock.docking.state.PersistenceException;
import org.flexdock.perspective.persist.xml.XMLPersister;

public class OutputStreamPersistenceHandler implements PersistenceHandler {
    private Persister myPersister;
    private StreamFactory myFactory;

    public static interface StreamFactory {
        OutputStream createOutputStream(String persistenceKey);
        InputStream createInputStream(String persistenceKey);
    }

    public OutputStreamPersistenceHandler(StreamFactory factory) {
        myFactory = factory;
        myPersister = XMLPersister.newDefaultInstance();
    }
    
    public PerspectiveModel load(String persistenceKey) throws IOException, PersistenceException {
        InputStream stream = myFactory.createInputStream(persistenceKey);
        try {
            PerspectiveModel perspectiveModel = myPersister.load(stream);
            return perspectiveModel;
        } finally {
            stream.close();
        }
    }

    public boolean store(String persistenceKey, PerspectiveModel perspectiveModel) 
    throws IOException, PersistenceException {
        OutputStream stream = myFactory.createOutputStream(persistenceKey);
        try {
            return myPersister.store(stream, perspectiveModel);
        } finally {
            stream.close();
        }
    }
    
    public Persister createDefaultPersister() {
        return XMLPersister.newDefaultInstance();
    }    

}
