/*=============================================================================
 * ITESM CEM, A. Ortiz, 1997, 2014.
 * Programa que demuestra la manera crear objetos persistentes en Java. 
 *=============================================================================*/

package edd.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Scanner;

public class PersistentObject implements Serializable {

    private static final long serialVersionUID = 1;
    private static final String FILE_NAME = "persistent.bin";
    
    private int a;
    private int b;    

    // ------------------------------------------------------------------------
    public void set(int a, int b) {
        this.a = a;
        this.b = b;
    }

    // ------------------------------------------------------------------------
    public String toString() {
        return "(" + a + ", " + b + ")";
    }

    // ------------------------------------------------------------------------
    public void persist() {

        try (FileOutputStream fos = new FileOutputStream(FILE_NAME);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(this);

        } catch (Exception e) {
            // Atrapar todas las excepciones y terminar programa.
            e.printStackTrace();
            System.exit(1);
        }
    }

    // ------------------------------------------------------------------------
    public static PersistentObject retrieve() {

        if (new File(FILE_NAME).exists()) {
            try (FileInputStream fis = new FileInputStream(FILE_NAME);
                 ObjectInputStream ois = new ObjectInputStream(fis)) {
                return (PersistentObject) ois.readObject();

            } catch (Exception e) {
                // Atrapar todas las excepciones y terminar programa.
                e.printStackTrace();
                System.exit(1);
            }
        }

        return null;
    }

    // ------------------------------------------------------------------------
    public static void main(String[] args) {

        try (Scanner in = new Scanner(System.in)) {

            System.out.println("Intentando recuperar objeto persistente...");
            PersistentObject pObj = PersistentObject.retrieve();
            if (pObj == null) {
                // Manejar el caso cuando el archivo no existe y se debe
                // crear por primera vez.
                System.out
                        .println("El objeto persistente serĂ¡ creado por primera vez");
                pObj = new PersistentObject();
                
            } else {
                System.out.println("Objeto recuperado: " + pObj);
                System.out.print("¿Deseas modificarlo? (S/N): ");
                String option = in.next();
                if (Character.toUpperCase(option.charAt(0)) != 'S') {
                    return;
                }
            }

            System.out.print("Introduce primer valor: ");
            int a = in.nextInt();
            System.out.print("Introduce segundo valor: ");
            int b = in.nextInt();
            pObj.set(a, b);
            System.out.println("Grabando el objeto persistente...");
            pObj.persist();            
        }
    }
}