package eu.gressly.io;

import java.io.*;
import java.util.zip.*;

/**
 *                   <code>Persistent</code>
 * This class is used to hold the data permanent.
 * Call "load()" at startup of the application and call "save()"
 * at the end.
 * @author Philipp Gressly (phi@gressly.ch)
 */
/*
 * History: first Implementation: 23.11.2005
 * Bugs   :
 */
public class Persistent {
    
    final static String PERSISTENT_FILE_NAME_SUFFIX = "joz";
    
    /**
     * Generate a Filename with a "." suffix.
     * If the given name already contains a suffix, the filename is not changed.
     * @param persistentFileName
     * @return Filename with suffix (.joz) per default.
     */
    private static String makePersistentFileName(String persistentFileName) {
       if(persistentFileName.indexOf('.') >= 0){
           return persistentFileName;
       } else {
           return persistentFileName + "." + PERSISTENT_FILE_NAME_SUFFIX;
       }
    }
    
    /**
     * Save any (serializable) object to a file with the above filename
     * @param data The object to save 
     * @throws IOException
     */
    public static void save(Object data, String persistentFileName) throws IOException {
        File file = new File(makePersistentFileName(persistentFileName));
        FileOutputStream fos = new FileOutputStream(file); // Save to file
        GZIPOutputStream gzos = new GZIPOutputStream(fos); // Compressed
        ObjectOutputStream out = new ObjectOutputStream(gzos);// Save objects
        out.writeObject(data); // Write the entire Vector of scribbles
        out.flush(); // Always flush the output.
        out.close(); // And close the stream.
    }

    /**
     * 
     * Load a previously saved object.
     * The filename is static in this class and will never be changed.
     * @return The deserialized object.getPersistentFileName
     * @throws Exception
     */
    public static Object load(String persistentFileName) throws Exception {
        Object result = null;
        File inFile = new File(makePersistentFileName(persistentFileName));
        FileInputStream fis = new FileInputStream(inFile);// Read from file
        GZIPInputStream gzis = new GZIPInputStream(fis); // Uncompress
        ObjectInputStream in = new ObjectInputStream(gzis); // Read objects
        // Read in an object. It should be an AllData object
        try {
            result = in.readObject();
        } catch (ClassNotFoundException cnfe) {
            throw new IOException("Class Not Found in SysTools.load() :\n" + cnfe);
        }
        in.close(); // Close the stream.
        //System.out.println("Data gelesen.");
        return result;
    }

}  // end of class Persistent