package org.aegee.runanddine.advertisement;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.aegee.runanddine.registration.SingleRegistration;
import org.aegee.runanddine.util.data.ModelNotExistingException;
import org.aegee.runanddine.util.model.MySQLModelManager;

/**
 * Manages persistent MailingList models
 */
public class MailingListManager extends MySQLModelManager<MailingList> {
    
    /**
     * Singleton instance of MailingListManager
     */
    private static MailingListManager instance = null;
    
    /**
     * Init MailingListManager
     * (private because of singleton pattern)
     */
    private MailingListManager()  {
        super();
        this.table = "mailing_lists";
    }
    
    /**
     * Return singleton instance of MailingListManager
     * @return Singleton instance of MailingListManager
     */
    public static MailingListManager getInstance() {
        // create singleton instance if it does not exist
        if (MailingListManager.instance == null) {
            MailingListManager.instance = new MailingListManager();
        }
        
        return MailingListManager.instance;
    }
    
    /**
     * Get MailingListManager by name
     * @param id Name of desired MailingList
     * @return MailingList identified by name
     * @throws ModelNotExistingException Gets thrown if no MailingList exists for given name
     */
    public MailingList getByName(String name) throws ModelNotExistingException {
        try {
            PreparedStatement stmt = this.con.prepareStatement("SELECT id, serialized_object FROM " + this.table + " WHERE name=?");
            // bind token
            stmt.setString(1, name);
            // search for model
            ResultSet rs = stmt.executeQuery();
            // check if model exists
            if (rs.next()) {
                // deserialize model
                MailingList 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(MailingList model) {
        try {
            // update model
            if (this.hasModel(model.getId())) {
                PreparedStatement stmt = this.con.prepareStatement("UPDATE " + this.table + " SET serialized_object=?, name=? WHERE id=?");
                // bind values
                stmt.setObject(1, model);
                stmt.setString(2, model.getName());
                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, name) VALUES (?, ?)");
                // bind values to statement
                stmt.setObject(1, model);
                stmt.setString(2, model.getName());
                // 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);
        }
    }
    
    /**
     * Create empty MailingList
     * @return Empty MailingList
     */
    public MailingList newObject() {
        MailingList model = new MailingList();
        
        return model;
    }
}