package com.mockobjects.examples.mailinglist;

import java.sql.*;

public class MailingList {
    static public final String INSERT_SQL = "insert into mailing_list(email_address, name) values(?, ?)";
    static public final String DELETE_SQL = "delete from mailing_list where email_address = ?";
    static public final String LIST_SQL = "select * from mailing_list";

    public void addMember(Connection connection, String emailAddress, String name) throws MailingListException, SQLException {
        PreparedStatement statement = connection.prepareStatement(INSERT_SQL);
        try {
            statement.setString(1, emailAddress);
            statement.setString(2, name);
            statement.execute();
        } catch (SQLException ex) {
            if (ex.getErrorCode() == DatabaseConstants.UNIQUE_CONSTRAINT_VIOLATED) {
                throw new MailingListException("Email address exists: " + emailAddress);
            } else {
                throw ex;
            }
        } finally {
            statement.close();
        }
    }

    public void removeMember(Connection connection, String emailAddress) throws MailingListException, SQLException {
        PreparedStatement statement = connection.prepareStatement(DELETE_SQL);
        try {
            statement.setString(1, emailAddress);
            if (statement.executeUpdate() == 0) {
                throw new MailingListException("Could not find email address: " + emailAddress);
            }
        } finally {
            statement.close();
        }
    }

    public void applyToAllMembers(Connection connection, ListAction listMembers) throws MailingListException, SQLException {
        Statement statement = connection.createStatement();
        try {
            ResultSet results = statement.executeQuery(LIST_SQL);

            while (results.next()) {
                listMembers.applyTo(results.getString("email_address"), results.getString("name"));
            }
        } finally {
            statement.close();
        }
    }
}
