/*
 * Created on Oct 27, 2004
 * Copyright (C) Andrea Schweer, 2004
 *
 * This file is part of the Greenstone Alerting Service.
 * Refer to the COPYING file in the base directory of this package
 * for licensing information.
 */
package org.greenstone.gsdlas;

import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
import java.util.*;

import javax.servlet.http.HttpSession;

import org.greenstone.gsdlas.database.DatabaseException;
import org.greenstone.gsdlas.database.DatabaseManager;
import org.greenstone.gsdlas.profiles.*;

/**
 * Storage for all Profiles. Singleton.
 * 
 * @author schweer
 *  
 */
public class ProfileStore {

    private static ProfileStore instance;

    private Set noEqualsSubscriptions = new TreeSet();
    private Map dontCareSubscriptions = new TreeMap();
    private Map subscriptions = new TreeMap();
    

    private ProfileStore() {
        // hide default constructor
    }

    /**
     * @return the one existing instance of this class.
     */
    public static ProfileStore getInstance() {
        if (instance == null) {
            instance = new ProfileStore();
        }
        return instance;
    }

    /**
     * @param subscription
     *            the subscription to add to the profile store.
     */
    private void addSubscription(Subscription subscription) {
        List documentIdPredicate = subscription.getPredicateList(Constants.DOCUMENT_ID_FIELD);
        List collectionIdPredicate = subscription.getPredicateList(Constants.COLLECTION_ID_FIELD);
        List hostIdPredicate = subscription.getPredicateList(Constants.HOST_ID_FIELD);
        List typePredicate = subscription.getPredicateList(Constants.TYPE_FIELD);
        
        Integer subId = new Integer(subscription.getId());
        
        if (documentIdPredicate.isEmpty()) {
            if (!dontCareSubscriptions.containsKey(Constants.DOCUMENT_ID_FIELD)) {
                dontCareSubscriptions.put(Constants.DOCUMENT_ID_FIELD, new TreeSet());
            }
            Set list = (Set) dontCareSubscriptions.get(Constants.DOCUMENT_ID_FIELD);
            list.add(subId);
        }
        if (hostIdPredicate.isEmpty()) {
            if (collectionIdPredicate.isEmpty()) {
                if (!dontCareSubscriptions.containsKey(Constants.COLLECTION_ID_FIELD)) {
                    dontCareSubscriptions.put(Constants.COLLECTION_ID_FIELD, new TreeSet());
                }
                Set list = (Set) dontCareSubscriptions.get(Constants.COLLECTION_ID_FIELD);
                list.add(subId);
            }
        }
        if (typePredicate.isEmpty()) {
            if (!dontCareSubscriptions.containsKey(Constants.TYPE_FIELD)) {
                dontCareSubscriptions.put(Constants.TYPE_FIELD, new TreeSet());
            }
            Set list = (Set) dontCareSubscriptions.get(Constants.TYPE_FIELD);
            list.add(subId);
        }
        
        if (documentIdPredicate.isEmpty() && collectionIdPredicate.isEmpty() 
                && hostIdPredicate.isEmpty() && typePredicate.isEmpty()) {
            noEqualsSubscriptions.add(subId);
        }
        subscriptions.put(subId, subscription);
    }

    /**
     * @return
     */
    public Set getSubscriptionsWithoutEqualsPredicates() {
        return Collections.unmodifiableSet(noEqualsSubscriptions);
    }

    /**
     * Computes the list of equality subscriptions satisfied by the event.
     * @param event
     * @return
     */
    private Set getPartiallyMatchedSubscriptions(Map event) {
        Set result = new TreeSet();
        
        EqualsPredicate predicate;
        
        // all subscriptions with matching type...
        predicate = PredicateFactory.getEqualsPredicate(Constants.TYPE_FIELD, 
                (String)event.get(Constants.TYPE_FIELD));
        if (predicate != null)
            result.addAll(predicate.getSubscriptionIDs());
        
        // ...but only those subscriptions where the doc id matches...
        Set docIDSubs = new TreeSet();
        predicate = PredicateFactory.getEqualsPredicate(Constants.DOCUMENT_ID_FIELD, 
                (String)event.get(Constants.DOCUMENT_ID_FIELD));
        if (predicate != null)
            docIDSubs.addAll(predicate.getSubscriptionIDs());
        docIDSubs.addAll(getDontCareSubscriptions(Constants.DOCUMENT_ID_FIELD));
        result.retainAll(docIDSubs);
        
        // ...and only those subscriptions where the host/collection id matches:
        Set hostCollIDSubs = new TreeSet();
        //   i.e.: host|coll is "don't care"...
        hostCollIDSubs.addAll(getDontCareSubscriptions(Constants.COLLECTION_ID_FIELD));
        //   ...or host matches (-> coll is "don't care" for this host)...
        predicate = PredicateFactory.getEqualsPredicate(Constants.HOST_ID_FIELD, 
                (String)event.get(Constants.HOST_ID_FIELD));
        if (predicate != null)
            hostCollIDSubs.addAll(predicate.getSubscriptionIDs());
        //   ...or host|coll matches
        predicate = PredicateFactory.getEqualsPredicate(Constants.COLLECTION_ID_FIELD, 
                (String)event.get(Constants.COLLECTION_ID_FIELD));
        if (predicate != null)
            hostCollIDSubs.addAll(predicate.getSubscriptionIDs());
        
        result.retainAll(hostCollIDSubs);
        
        return result;
    }

    /**
     * 
     * @param gsComm 
     * @return
     * @throws UnsupportedFieldException
     */
    private Set findMatchedQueryPredicates(Map event, GreenstoneCommunicator gsComm) {
        Set matchedPreds = new TreeSet();
        
        // iterate through all document content predicates
        // execute the query stored in the predicate
        // predicate is matched iff the docID occurs in the query result
        
        for (Iterator iter = PredicateFactory.getQueryPredicates(Constants.DOCUMENT_CONTENT_FIELD).iterator(); iter.hasNext();) {
            Predicate predicate = (Predicate) iter.next();
            String collection = (String) event.get(Constants.COLLECTION_ID_FIELD);
            String query = predicate.getValue();
            Set results;
            try {
                results = gsComm.fullTextSearch(collection, query);
                if (results.contains(event.get(Constants.DOCUMENT_ID_FIELD))) {
                    matchedPreds.add(predicate);
                }
            } catch (Exception e) {
            }
        }
        
        return matchedPreds;
    }

    /**
     * Computes the set of SubstringMatchPredicates satisfied by the event.
     * @param event
     * 
     * @return
     */
    private Set findMatchedSubstringMatchPredicates(Map event) {
        Set result = new TreeSet();
        
        for (Iterator iter = PredicateFactory.getAllSubstringMatchPredicates().iterator(); iter.hasNext();) {
            Predicate predicate = (Predicate) iter.next();
            if (predicate.isSatisfied(event)) {
                result.add(predicate);
            }
        }
        return result;
    }

    /**
     * Filters the event against the profiles. It uses the equality-preferred
     * algorithm as described in Fabret, Llirbat, Pereira and Shasha:
     * <em>Efficient Matching for Content-based Publish/Subscribe 
     * Systems</em>.
     * @param event
     * @param gsComm 
     */
    public Set filter(Map event, GreenstoneCommunicator gsComm) {
        Set matchedSubscriptions = new TreeSet();
    
        Set partiallyMatchedSubscriptions 
        	= getPartiallyMatchedSubscriptions(event);
    
        Set matchedPredicates = findMatchedSubstringMatchPredicates(event);
        matchedPredicates.addAll(findMatchedQueryPredicates(event, gsComm));
    
        Map numMatchedPredicates = new TreeMap();
        for (Iterator iter = matchedPredicates.iterator(); iter.hasNext();) {
            Predicate pred = (Predicate) iter.next();
            for (Iterator iterator = pred.getSubscriptionIDs().iterator(); iterator
                    .hasNext();) {
                Integer subId = (Integer) iterator.next();
                Subscription sub = (Subscription) subscriptions.get(subId);
                Integer count = (Integer) numMatchedPredicates.get(subId);
                int newCountValue = (count == null ? 1 : count.intValue() + 1);
                numMatchedPredicates.put(subId,
                        new Integer(newCountValue));
            }
        }
    
        Set notUnmatchedSubscriptions = partiallyMatchedSubscriptions;
        notUnmatchedSubscriptions.addAll(noEqualsSubscriptions);
        for (Iterator iter = notUnmatchedSubscriptions.iterator(); iter
                .hasNext();) {
            Integer subId = (Integer) iter.next();
            Subscription sub = (Subscription) subscriptions.get(subId);
            int matchedPredicatesCount = 0;
            if (numMatchedPredicates.get(subId) != null) {
                matchedPredicatesCount = ((Integer) numMatchedPredicates.get(subId)).intValue();
            }
            if (matchedPredicatesCount == sub.getNumOfNonEqualsPredicates()) {
                matchedSubscriptions.add(sub);
            }
        }
        return matchedSubscriptions;
    }


    /**
     * @param arguments
     * @throws Exception
     */
    public void createSubscription(Map arguments) throws Exception {
        Subscription sub = new Subscription(arguments);
        addSubscription(sub);
    }

    
    /**
     * @param subscriptionID
     * @throws DatabaseException
     * @throws SQLException
     */
    public void deleteSubscription(String subscriptionID) throws DatabaseException, SQLException {
        Integer subID = new Integer(subscriptionID);
        System.out.println("deleting subscription " + subscriptionID);
        if (!subscriptions.containsKey(subID)) {
            return;
        }
        Subscription sub = (Subscription) subscriptions.get(subID);
        for (Iterator iter = dontCareSubscriptions.values().iterator(); iter.hasNext();) {
            Set entry = (Set) iter.next();
            if (entry.contains(subID))
                entry.remove(subID);
        }
        if (noEqualsSubscriptions.contains(subID))
            noEqualsSubscriptions.remove(subID);
        for (Iterator iter = sub.getPredicates().iterator(); iter.hasNext();) {
            Predicate pred = (Predicate) iter.next();
            pred.removeSubscription(subID);
        }

        subscriptions.remove(subID);
        
        
        Connection conn = DatabaseManager.getInstance().getDatabaseConnection();
        
        Statement statement = conn.createStatement();
        
        String sqlString = "DELETE FROM subscriptions WHERE id = " + subscriptionID;
        statement.executeUpdate(sqlString);
        
        sqlString = "SELECT predicate FROM subs_to_predicates " +
        		"WHERE subscription = " + subscriptionID;
        ResultSet predicates = statement.executeQuery(sqlString);
        while (predicates.next()) {
            // if there aren't any other subscriptions using this predicate, delete predicate
            int predicateID = predicates.getInt("predicate");
            
        }
        
        
    }

    /**
     * @param arguments
     * @param session
     */
    public void changeSubscription(Map arguments, HttpSession session) {
        String subscriptionID = (String) arguments.get("subscriptionID");
        // BTS 14 really edit the subscription
        
    }

    /**
     * @param username
     * @return
     * @throws DatabaseException
     */
    public Set getAllSubscriptionsFor(String username) throws DatabaseException {
        Set result = new TreeSet();
        try {
            Connection conn = DatabaseManager.getInstance().getDatabaseConnection();
            Statement statement = conn.createStatement();
            String sqlString = "SELECT id FROM subscriptions " +
            		"WHERE user like '" + username + "';";
            ResultSet idList = statement.executeQuery(sqlString);
            while (idList.next()) {
                int id = idList.getInt("id");
                result.add(subscriptions.get(new Integer(id)));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * @param string
     * @return
     */
    private Set getDontCareSubscriptions(String field) {
        Set result = new TreeSet();
        if (dontCareSubscriptions.containsKey(field)) {
            result = (Set) dontCareSubscriptions.get(field);
        }
        return result;
    }

    /**
     * 
     */
    public void restoreFromDatabase() {
        try {
            Connection conn = DatabaseManager.getInstance().getDatabaseConnection();
            Statement statement = conn.createStatement();
            String sqlString = "SELECT * FROM subscriptions";
            ResultSet subs = statement.executeQuery(sqlString);
            while (subs.next()) {
                // construct map for all predicates
                int id = subs.getInt("id");
                Map map = new TreeMap();
                map.put("username", subs.getString("user"));
                map.put("email", subs.getString("email"));
                map.put("subscription_name", subs.getString("name"));
                Vector ways = new Vector();
                if (subs.getInt("rss") != 0) {
                    ways.add("rss");
                }
                if (subs.getInt("page") != 0) {
                    ways.add("page");
                }
                map.put("way", ways);
                Statement stmnt = conn.createStatement();
                sqlString = "SELECT p.type, p.field, p.value from subs_to_predicates stp join predicates p on(stp.predicate = p.id) where stp.subscription = " + id + ";";
                ResultSet predicates = stmnt.executeQuery(sqlString);
                while (predicates.next()) {
                    String type = predicates.getString(Constants.TYPE_FIELD);
                    String field = predicates.getString("field");
                    if (type.equals(SubstringMatchPredicate.class.getName())) {
                        if (field.equals(Constants.COLLECTION_ID_FIELD)) {
                            field = Constants.COLLECTION_QUERY_FIELD;
                        } else if (field.equals(Constants.HOST_ID_FIELD)) {
                            field = Constants.HOST_QUERY_FIELD;
                        }
                    }
                    String value = predicates.getString("value");
                    if (type.equals(EqualsPredicate.class.getName())) {
                        if (!map.containsKey(field)) {
                            map.put(field, new Vector());
                        }
                        ((List) map.get(field)).add(value);
                    } else {
                        map.put(field, value);
                    }
                }
                try {
                    createSubscription(map);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DatabaseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @param i
     * @return
     */
    public Subscription getSubscription(int id) {
        return (Subscription) subscriptions.get(new Integer(id));
    }
    
}