package org.apache.james.transport.matchers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.mail.MessagingException;

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
import org.apache.avalon.cornerstone.services.datasource.DataSourceSelector;
import org.apache.avalon.excalibur.datasource.DataSourceComponent;
import org.apache.avalon.framework.component.ComponentManager;

import org.apache.james.Constants;

import org.apache.mailet.GenericRecipientMatcher;
import org.apache.mailet.MailAddress;


/**
 * Special Matcher for org.apache.james.transport.mailets.JDBCListsListserv
 *
 * @author Danny Angus danny at apache.org
 * @see org.apache.james.transport.mailets.JDBCListsListserv
 */
public class InJDBCListsListserv extends GenericRecipientMatcher {
    private String ListTable               = "";
    private DataSourceComponent datasource = null;

    /**
     * Add Description
     *
     * @return Document return!
     */
    public String getMatcherInfo() {
        return "In JDBC Lists Listserver matcher";
    }

    /**
     * Add Description
     *
     * @throws MessagingException Document throws!
     */
    public void init() throws MessagingException {
        try {
            ListTable = getCondition();
            ComponentManager componentManager = (ComponentManager)getMailetContext().getAttribute(
                                                        Constants.AVALON_COMPONENT_MANAGER);
            // Get the DataSourceSelector block
            DataSourceSelector datasources    = (DataSourceSelector)componentManager.lookup(
                                                        DataSourceSelector.ROLE);
            // Get the data-source required.
            int stindex                       = ListTable.indexOf("://") + 3;
            int endindex                      = ListTable.indexOf("/", stindex);
            String datasourceName             = ListTable.substring(stindex, endindex);
            datasource                        = (DataSourceComponent)datasources.select(
                                                        datasourceName);
            log("init inJDBCL");
        } catch(Exception e) {
            log("can't get datasource ");
        }
    }

    /**
     * Add Description
     *
     * @param recipient Document parameter!
     * @return Document return!
     */
    public boolean matchRecipient(MailAddress recipient) {
        Connection conn = null;
        try {
            conn = datasource.getConnection();
            if(conn == null) {
                System.err.println("Cant get connection");
            }
            int stindex         = ListTable.lastIndexOf("/") + 1;
            int endindex        = ListTable.length();
            String Table        = ListTable.substring(stindex, endindex);
            String query        = "Select count(*) from " + Table + " where list_address = '" +
                                  recipient.toString() + "'";
            PreparedStatement q = conn.prepareStatement(query);
            ResultSet rs        = q.executeQuery();
            rs.first();
            int count = rs.getInt(1);
            if(count > 0) {
                return true;
            }
        } catch(Exception e) {
            log("Cant connect to lists table for matching");
            System.err.println("can't close connection");
        } finally {
            try {
                if(conn != null) {
                    conn.close();
                    log("closed conn");
                }
            } catch(SQLException sqle) {
                System.err.println("can't close connection");
            }
        }
        return false;
    }
}
