/**************************************************************************************************
* Copyright (c) 1997-2016, 2018 Flexera. All Rights Reserved.
**************************************************************************************************/
package alerter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

/**
 * Aleter is a web client of the web services offered by the License Manager.
 * It periodically checks for any new alerts and sends out notification email.
 */
public class Persist {
    /** 
     * Create and load from properties file.
     * 
     * @param fileName The properties file to load.
     */
    public Persist(String fileName) {
        properties = new Properties();
        file = new File(fileName);
        load();
    }

    /**
     * Get the last alert ID processed.
     * 
     * @return The last ID processed.
     */
    public String getLastId() {
        return properties.getProperty("lastAlert", "0");
    }
    
    /**
     * Set the last alert ID processed.
     * 
     * @param lastId The new last ID processed.
     */
    public void setLastId(String lastId) {
        properties.setProperty("lastAlert", lastId);
        save();
    }

    /** Load data from properties file. */
    private void load() {
        if (file.exists()) {
            try {
                BufferedInputStream in = 
                    new BufferedInputStream(new FileInputStream(file));
                properties.load(in);
                in.close();
            }
            catch (Exception e) {
                System.out.print("Error loading "+file.getPath()+": "+e);
            }
        }
    }
    
    private void save() {
        file.getParentFile().mkdirs();
        try {
            BufferedOutputStream out = 
                new BufferedOutputStream(new FileOutputStream(file));
            properties.store(out, "Alerter State");
            out.close();
        }
        catch (Exception e) {
            System.out.print("Error saving "+file.getPath()+": "+e);
        }
    }
    
    private Properties properties;
    private File file;
}
