package org.aegee.runanddine.pathfinder;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.aegee.runanddine.util.data.ModelNotExistingException;
import org.aegee.runanddine.util.model.MySQLModelManager;

/**
 * Manages persistent DistanceMatrix models
 */
public class DistanceMatrixManager extends MySQLModelManager<DistanceMatrix> {
    /**
     * Singleton instance of distance matrix manager
     */
    private static DistanceMatrixManager instance = null;
    
    /**
     * Init DistanceMatrixManager
     * (private because of singleton pattern)
     */
    private DistanceMatrixManager()
    {
        super();
        this.table = "distance_matrices";
    }
    
    /**
     * Return singleton instance of DistanceMatrixManager
     * @return Singleton instance of DistanceMatrixManager
     */
    public static DistanceMatrixManager getInstance() {
        // create singleton instance if it does not exist
        if (DistanceMatrixManager.instance == null) {
            DistanceMatrixManager.instance = new DistanceMatrixManager();
        }
        
        return DistanceMatrixManager.instance;
    }
    
    /**
     * Get DistranceMatrix by RunAndDine ID
     * @param id RunAndDine ID of desired DistanceMatrix
     * @return DistanceMatrix identified by RunAndDine ID
     * @throws ModelNotExistingException
     */
    public DistanceMatrix getByRunAndDineId(int runAndDineId) throws ModelNotExistingException {
        try {
            PreparedStatement stmt = this.con.prepareStatement("SELECT id, serialized_object FROM " + this.table + " WHERE rad_id=?");
            // bind token
            stmt.setInt(1, runAndDineId);
            // search for model
            ResultSet rs = stmt.executeQuery();
            // check if model exists
            if (rs.next()) {
                // deserialize model
                DistanceMatrix model = this.readObject(rs.getBytes("serialized_object"));
                model.setId(rs.getInt("id"));
                rs.close();
                stmt.close();

                return model;
            } else {
                throw new ModelNotExistingException();
            }
        } catch (SQLException e) {
            e.printStackTrace(System.err);
            return null;
        }
    }
    
    /**
     * Stores new model or updates existing one
     * @param model Model to be saved/updated
     */
    @Override
    public void save(DistanceMatrix model) {
        try {
            // update model
            if (this.hasModel(model.getId())) {
                PreparedStatement stmt = this.con.prepareStatement("UPDATE " + this.table + " SET serialized_object=?, rad_id=? WHERE id=?");
                // bind values
                stmt.setObject(1, model);
                stmt.setInt(2, model.getRunAndDineId());
                stmt.setInt(3, model.getId());
                // execute update
                stmt.executeUpdate();    
                stmt.close();
            // save new model
            } else {
                PreparedStatement stmt = this.con.prepareStatement("INSERT INTO " + this.table + " (serialized_object, rad_id) VALUES (?, ?)");
                // bind values to statement
                stmt.setObject(1, model);
                stmt.setInt(2, model.getRunAndDineId());
                // execute insert
                stmt.executeUpdate();
                // retrieve auto increment id
                ResultSet rs = stmt.getGeneratedKeys();
                rs.next();
                model.setId(rs.getInt(1));
                rs.close();
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
    }
    
    /**
     * Not supported because DistanceMatrix needs to be initialized
     * with the appropriate size
     */
    public DistanceMatrix newObject() {
        throw new UnsupportedOperationException();
    }
}