<?PHP
#
#   FILE:  AJAXDropdown.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

# ----- MAIN -----------------------------------------------------------------

$AF->SuppressHTMLOutput();

# if a version is specified
if (isset($_GET["Version"]))
{
    # VERSION 2
    $JsonHelper = new JsonHelper();
    $Schema = new MetadataSchema();

    # make sure user is logged in with sufficient privileges
    if (!$User->HasPriv(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN))
    {
        $JsonHelper->Error("Insufficient privileges");
        return;
    }

    # input parameters
    $Version = GetArrayValue($_GET, "Version");
    $Input = GetArrayValue($_GET, "input");
    $FieldId = GetArrayValue($_GET, "fieldid");
    $Context = GetArrayValue($_GET, "context");

    # the input parameter is required
    if (is_null($Input) || !strlen(trim($Input)))
    {
        $JsonHelper->Error("The \"input\" parameter is necessary");
        return;
    }

    # the fieldid parameter is also required
    if (is_null($FieldId))
    {
        $JsonHelper->Error("The \"fieldid\" parameter is necessary");
        return;
    }

    $Field = $Schema->GetField($FieldId);

    # a valid field ID is required
    if ($Field->Status() != MetadataSchema::MDFSTAT_OK)
    {
        $JsonHelper->Error("Invalid metadata field ID");
        return;
    }

    # get the maximum number of results to display from the field
    $MaxResultsToDisplay = $Field->NumAjaxResults();

    $Search = "";
    $Words = preg_split('/\s+/', $Input, -1, PREG_SPLIT_NO_EMPTY);

    foreach ($Words as $Word)
    {
        # just add the word if it's quoted or has an asterisk already
        if (preg_match('/\"$/', $Word) || preg_match('/\*$/', $Word))
        {
            $Search .= $Word." ";
        }

        # add wildcard operator for stemming
        else
        {
            $Search .= $Word."* ";
        }
    }

    if ($Context == "users")
    {
        $UserFactory = new CWUserFactory();
        $SearchResults = $UserFactory->FindUserNames($Search);
    }

    else
    {
        $SearchResults = $Field->GetFactory()->SearchForItemNames(
            trim($Search), $MaxResultsToDisplay+1);
    }

    $NumberOfResults = count($SearchResults);

    # if there are no results
    if ($NumberOfResults < 1)
    {
        $JsonHelper->AddDatum("error", TRUE);
        $JsonHelper->AddDatum("errorMessage",
          "No results found. Please broaden your search.");
        $JsonHelper->Success();
        return;
    }

    # if there are too many results
    else if ($NumberOfResults > $MaxResultsToDisplay)
    {
        $JsonHelper->AddDatum("error", TRUE);
        $JsonHelper->AddDatum("errorMessage",
        "More than $MaxResultsToDisplay results were found. Please narrow your search.");
        $JsonHelper->Success();
        return;
    }

    else
    {
        $JsonHelper->AddDatum("error", FALSE);
        $JsonHelper->AddDatum("results", $SearchResults);
        $JsonHelper->Success();
        return;
    }

    # return
    $JsonHelper->Error("An error occurred.");
    return;
}

# backwards compatibility, no version specified
else
{
    # make sure user is logged in with sufficient privileges
    if (!$G_User->HasPriv(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN))
    {
        return;
    }

    $MaxResultsToDisplay = 50;

    # if a search string was entered and field ID is available
    $SearchString = trim($_GET["Argument"]);
    $FieldId = trim($_GET["FieldId"]);
    if (($SearchString != "") && ($FieldId != ""))
    {
        # if field ID is valid
        $Schema = new MetadataSchema();
        $Field = $Schema->GetField($FieldId);
        if ($Field !== NULL)
        {
            # update max results to display
            $MaxResultsToDisplay = $Field->NumAjaxResults();

            $Search = "";
            $Words = preg_split("/\s+/", $SearchString, -1, PREG_SPLIT_NO_EMPTY);

            foreach ($Words as $Word)
            {
                # just add the word if it's quoted or has an asterisk already
                if (preg_match("/\"$/", $Word)
                    || preg_match("/\*$/", $Word))
                {
                    $Search .= $Word." ";
                }

                # add wildcard operator for stemming
                else
                {
                    $Search .= $Word."* ";
                }
            }

            # perform search
            $SearchResults = $Field->GetFactory()->SearchForItemNames(
                trim($Search), $MaxResultsToDisplay+1);
        }
    }
    else
    {
        print "{ 'type' : 'error', 'message' : "
        ."'No search term was entered. Please enter one.',"
             ." 'resources' : [], 'numresources' : 0 }";
        return;
    }

    # if there are no results
    $NumberOfResults = count($SearchResults);
    if ($NumberOfResults < 1)
    {
        print "{ 'type' : 'error', 'message' :"
        ." 'No results were found. Please enter a different"
        ." search term or broaden the search.', 'resources' : [], 'numresources' : 0 }";
    }
    # else if there are too many results
    else if ($NumberOfResults > $MaxResultsToDisplay)
    {
        print "{ 'type' : 'warning', 'message' : "
        ."'More than $MaxResultsToDisplay results were found."
             ." please narrow the search.', 'resources' : [], 'numresources' : 0 }";
    }
    else
    {
        $Return = "{ 'type' : 'ok', 'message' : '', 'resources' : [";
        foreach($SearchResults as $TempResult)
        {
            # Create and add JSON objects
            $Return .= "{ 'value' : '$TempResult' },";
        }
        print $Return . "], 'numresources' : $NumberOfResults }";
    }

    return;
}
