/*
 * File:     ContentQuery.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package mpi.search.content.query.model;

import mpi.search.SearchLocale;

import mpi.search.content.model.CorpusType;

import mpi.search.content.result.model.ContentResult;

import mpi.search.model.Query;
import mpi.search.model.Result;

import java.io.File;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


/**
 * $Id: ContentQuery.java,v 1.3 2005/08/09 13:04:34 klasal Exp $
 *
 * @author $Author: klasal $
 * @version $Revision: 1.3 $
 */
public class ContentQuery implements Query {
    final ContentResult result;
    final protected ArrayList constraintList;
    final private CorpusType type;
    final private File[] files;

    public ContentQuery(CorpusType type) {
        this(type, null);
    }

    /**
     * Creates a new Query instance
     */
    public ContentQuery(CorpusType type, File[] files) {
        this.type = type;
        constraintList = new ArrayList();
        constraintList.add(null);
        result = new ContentResult();
        this.files = files;
    }

    public Result getResult() {
        return result;
    }

    public File[] getFiles() {
        return files;
    }

    final public CorpusType getType() {
        return type;
    }

    final public void setAnchorConstraint(AnchorConstraint anchorConstraint) {
        constraintList.set(0, anchorConstraint);
    }

    final public boolean isRestricted() {
        return constraintList.get(0) instanceof RestrictedAnchorConstraint;
    }

    final public AnchorConstraint getAnchorConstraint() {
        return (AnchorConstraint) constraintList.get(0);
    }

    /**
     * DOCUMENT ME!
     *
     * @param constraint
     *            DOCUMENT ME!
     */
    final public void addDependentConstraint(
        DependentConstraint dependentConstraint) {
        constraintList.add(dependentConstraint);
    }

    final public int size() {
        return constraintList.size();
    }

    final public DependentConstraint getDependentConstraint(int nr) {
        return ((0 < nr) && (nr < constraintList.size()))
        ? (DependentConstraint) constraintList.get(nr) : null;
    }

    final public Constraint getConstraint(int nr) {
        return ((0 < nr) && (nr <= size()))
        ? (Constraint) constraintList.get(nr - 1) : null;
    }

    final public Constraint getRefConstraint(DependentConstraint constraint) {
        return getConstraint(constraint.getRefConstraintNr());
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    final public List getConstraints() {
        return constraintList;
    }

    /**
     * Returns false, if there is one constraint with an empty search expression
     *
     * @return boolean
     */
    final public boolean isWellSpecified() {
        boolean wellSpecified = true;

        for (int i = 0; i < constraintList.size(); i++) {
            if (constraintList.get(i) != null) {
                if (((Constraint) constraintList.get(i)).isRegEx() &&
                        ((Constraint) constraintList.get(i)).getPattern()
                             .equals("")) {
                    wellSpecified = false;
                }
            }
        }

        return wellSpecified;
    }

    /**
     * Translates query to human readable text.
     *
     * @return DOCUMENT ME!
     */
    public String toString() {
        StringBuffer sb = new StringBuffer(SearchLocale.getString(
                    "Search.Query.Find") + "\n");

        for (int i = 0; i < constraintList.size(); i++) {
            if (constraintList.get(i) != null) {
                Constraint constraint = (Constraint) constraintList.get(i);

                if (constraint instanceof DependentConstraint) {
                    sb.append(SearchLocale.getString("Search.Query.With")
                                          .toUpperCase() + " ");
                    sb.append(SearchLocale.getString(constraint.getMode()) +
                        " ");
                }

                sb.append(SearchLocale.getString("Search.Query.Constraint") +
                    " " + constraint.getNr() + ":\n");

                sb.append(SearchLocale.getString(constraint.getQuantifier()));
                sb.append(" " +
                    SearchLocale.getString("Search.Constraint.AnnotationOnTier") +
                    " ");

                if (constraint instanceof AnchorConstraint) {
                    String[] tierNames = ((AnchorConstraint) constraint).getTierNames();

                    for (int j = 0; j < tierNames.length; j++) {
                        sb.append(tierNames[j] + " ");
                    }
                } else {
                    sb.append(constraint.getTierName() + " ");
                }

                if (constraint instanceof AnchorConstraint) {
                    sb.append(SearchLocale.getString("Search.Constraint.That") +
                        " ");
                }

                sb.append(SearchLocale.getString("Search.Constraint.Matches") +
                    " ");

                sb.append(constraint.isCaseSensitive()
                    ? (SearchLocale.getString("Search.Constraint.CaseSensitive") +
                    " ")
                    : (SearchLocale.getString(
                        "Search.Constraint.CaseInsensitive") + " "));
                sb.append(constraint.isRegEx()
                    ? (SearchLocale.getString(
                        "Search.Constraint.RegularExpression") + " ")
                    : (SearchLocale.getString("Search.Constraint.String") +
                    " "));

                sb.append("'" + constraint.getPattern() + "'" + "\n");

                if (constraint instanceof AnchorConstraint) {
                    if ((constraint.getLowerBoundary() != Long.MIN_VALUE) ||
                            (constraint.getUpperBoundary() != Long.MAX_VALUE)) {
                        sb.append(SearchLocale.getString("Search.And") + " ");
                        sb.append(SearchLocale.getString(constraint.getUnit()) +
                            " ");
                        sb.append(SearchLocale.getString("Search.Interval") +
                            " ");
                        sb.append(SearchLocale.getString("Search.From") + " ");
                        sb.append(constraint.getLowerBoundary() + " ms ");
                        sb.append(SearchLocale.getString("Search.To") + " ");
                        sb.append(constraint.getUpperBoundaryAsString() +
                            " ms ");
                        sb.append("\n");
                    }
                } else {
                    if (constraint.getMode().equals(Constraint.STRUCTURAL)) {
                        sb.append(SearchLocale.getString(
                                "Search.Constraint.Distance") + " ");
                        sb.append(constraint.getLowerBoundaryAsString() + " ");
                        sb.append(SearchLocale.getString("Search.To") + " ");
                        sb.append(constraint.getUpperBoundaryAsString() + " ");
                        sb.append(constraint.getUnit() + " ");
                        sb.append(SearchLocale.getString("Search.From") + " ");
                    } else {
                        sb.append(SearchLocale.getString("Search.And") + " ");
                        sb.append(SearchLocale.getString(constraint.getUnit()) +
                            " ");

                        boolean constraintWithDistance = Constraint.WITHIN_OVERALL_DISTANCE.equals(constraint.getUnit()) ||
                            Constraint.WITHIN_DISTANCE_TO_LEFT_BOUNDARY.equals(constraint.getUnit()) ||
                            Constraint.WITHIN_DISTANCE_TO_RIGHT_BOUNDARY.equals(constraint.getUnit()) ||
                            Constraint.BEFORE_LEFT_DISTANCE.equals(constraint.getUnit()) ||
                            Constraint.AFTER_RIGHT_DISTANCE.equals(constraint.getUnit());

                        if (constraintWithDistance) {
                            sb.append(constraint.getUpperBoundaryAsString() +
                                " ms ");
                        }
                    }

                    sb.append(SearchLocale.getString(
                            "Search.Constraint.MatchesFoundIn") + " ");
                    sb.append(((DependentConstraint) constraint).getRefConstraintNr());
                    sb.append("\n");
                }

                sb.append("\n");

                HashMap attributes = constraint.getAttributes();

                if (attributes != null) {
                    Iterator iter = attributes.keySet().iterator();

                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        String attributeValue = (String) attributes.get(key);

                        if (!attributeValue.equals("*") &&
                                !attributeValue.equals("") &&
                                !attributeValue.equals("ANY")) {
                            sb.append(" " + key + "=");

                            if (attributeValue.equals(">0")) {
                                sb.append("[^0]");
                            } else if (attributeValue.equals(">1")) {
                                sb.append("[^01]");
                            } else {
                                sb.append(attributeValue);
                            }
                        }
                    }
                }
            }
        }

        return sb.toString();
    }

    public boolean equals(Object object) {
        if (!(object instanceof ContentQuery)) {
            return false;
        }

        return getConstraints().equals(((ContentQuery) object).getConstraints());
    }
}
