/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright (c) Ericsson AB, 2004-2007. All rights reserved.
 */
package com.ericsson.ssa.dd;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;


/**
 * An "and" condition is true if and only if all its constituent conditions are
 * true. This operator is evaluated for each element in the condition list.
 */
public class AndOperator extends Operator {
    private static final long serialVersionUID = 3256720667486663224L;

    /**
     * Evaluate the condition
     *
     * @param object
     *        The object to evaluate
     * @return True if the operand or operator evaluation is satisfied, false
     *         otherwise
     */
    public boolean evaluate(Object object) {
        for (int i = 0; i < subConditions.size(); i++) {
            if (!((Condition) subConditions.get(i)).evaluate(object)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns the method session case list
     *
     * @return A hashtable of the method session case
     * @throws SipParserException
     */
    public Hashtable<String, ArrayList<String>> getMethodSessionCaseList()
        throws SipParserException {
        // Acceptable condition:
        // 1) -One method + one session case can exist under a AND condition
        // 2) -One method can exist under a AND condition
        // 3) -Others are Error cases
        Hashtable<String, ArrayList<String>> methodSessioncaseTableResult = new Hashtable<String, ArrayList<String>>();

        // Extract the method and sessioncase information from sub
        // subConditions (operator or operand)
        // and copy to the methodSessionFilterTable
        Hashtable<String, ArrayList<String>> methodSessionFilterTable = new Hashtable<String, ArrayList<String>>();

        for (int i = 0; i < subConditions.size(); i++) {
            // For each subList of condition we will extract method or
            // session-case in order to analyse it
            Hashtable<String, ArrayList<String>> curMethSessionTable = subConditions.get(i)
                                                                                    .getMethodSessionCaseList();
            Enumeration<String> keysList = curMethSessionTable.keys();

            while (keysList.hasMoreElements()) {
                String curKey = keysList.nextElement();

                if (curKey.equals("request.method") ||
                        curKey.equals("request.session-case")) {
                    // 3) -Others are Error cases
                    if (methodSessionFilterTable.containsKey(curKey)) {
                        throw new SipParserException(
                            "AND: Wrong Condition: two methods or session-case under the same AND condtion");
                    }

                    methodSessionFilterTable.put(curKey,
                        curMethSessionTable.get(curKey));
                } else {
                    if (methodSessioncaseTableResult.containsKey(curKey)) {
                        addOnlyNewElementToTheList(curMethSessionTable.get(
                                curKey),
                            methodSessioncaseTableResult.get(curKey));
                    } else {
                        methodSessioncaseTableResult.put(curKey,
                            curMethSessionTable.get(curKey));
                    }
                }
            }
        }

        if (!methodSessionFilterTable.isEmpty()) {
            if (!methodSessioncaseTableResult.isEmpty()) {
                throw new SipParserException(
                    "AND: Wrong Condition: two methods or session-case under the same AND condtion (not in the same level)");
            }

            // The methodSessionFiltreTable contains only method and
            // session-case keys
            if (methodSessionFilterTable.containsKey("request.method") &&
                    methodSessionFilterTable.containsKey("request.session-case")) {
                // 1) -One method + one session case can exist under a AND
                // condition
                Iterator<String> methodIter = methodSessionFilterTable.get(
                        "request.method").iterator();

                while (methodIter.hasNext()) {
                    methodSessioncaseTableResult.put(methodIter.next(),
                        methodSessionFilterTable.get("request.session-case"));
                }
            } else if (methodSessionFilterTable.containsKey("request.method") &&
                    !methodSessionFilterTable.containsKey(
                        "request.session-case")) {
                // 2) -One method can exist under a AND condition
                Iterator<String> methodIter = methodSessionFilterTable.get(
                        "request.method").iterator();

                while (methodIter.hasNext()) {
                    ArrayList<String> sessionCaseNotSpecify = new ArrayList<String>();
                    sessionCaseNotSpecify.add(SessionCase.EXTERNAL.toString());
                    methodSessioncaseTableResult.put(methodIter.next(),
                        sessionCaseNotSpecify);
                }
            } else {
                // 3) -Others are Error cases
                throw new SipParserException(
                    "AND: impossible Condition: one session-case without any method associated");
            }
        }

        return methodSessioncaseTableResult;
    }

    /**
     * @return
     */
    public String toString() {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < subConditions.size(); i++) {
            if (i > 0) {
                sb.append(" && ");
            }

            sb.append("(" + subConditions.get(i) + ")");
        }

        return sb.toString();
    }
}
