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

# ----- LOCAL FUNCTIONS ------------------------------------------------------



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

# set headers to control caching
$MaxAgeInSeconds = 30;
header("Expires: ".gmdate("D, d M Y H:i:s \G\M\T", time()+$MaxAgeInSeconds));
header("Cache-Control: private, max-age=".$MaxAgeInSeconds);
header("Pragma:");

# number of results to return
$DesiredNumberOfResults = 5;

# don't output any HTML
$GLOBALS["AF"]->SuppressHTMLOutput();

# PHP sessions cause AJAX calls to block, so make the session readonly from
# this point on to avoid latency
session_write_close();

$SearchString = GetArrayValue($_GET, "SS");

# construct search groups based on the keyword
$SearchParams = new SearchParameterSet();
$SearchParams->AddParameter($SearchString);

# signal event to allow modification of search parameters
$SignalResult = $GLOBALS["AF"]->SignalEvent(
    "EVENT_FIELDED_SEARCH", array(
        "SearchParameters" => $SearchParams,
        "User" => $GLOBALS["G_User"],
        "SavedSearch" => NULL));
$SearchParams = $SignalResult["SearchParameters"];

# perform search
$SearchEngine = new SPTSearchEngine();
$SearchResults = $SearchEngine->Search($SearchParams);

# filter out any temporary or unviewable records
foreach ($SearchResults as $SchemaId => $SchemaResults)
{
    $RFactory = new ResourceFactory($SchemaId);
    $ViewableResourceIds = $RFactory->FilterNonViewableResources(
        array_keys($SchemaResults), $GLOBALS["G_User"]);
    $FlippedViewableResourceIds = array_flip($ViewableResourceIds);
    $TempSearchResults = array();
    foreach ($SchemaResults as $Id => $Score)
    {
        if (($Id >= 0) && isset($FlippedViewableResourceIds[$Id]))
        {
            $TempSearchResults[$Id] = $Score;
        }
    }
    $SearchResults[$SchemaId] = $TempSearchResults;
}

# signal search performed
$SignalResult = $GLOBALS["AF"]->SignalEvent(
    "EVENT_SEARCH_RESULTS", array(
        "SearchResults" => $SearchResults));
$SearchResults = $SignalResult["SearchResults"];

# pull out stuff from the resource schema
if (isset($SearchResults[MetadataSchema::SCHEMAID_DEFAULT]))
{
    $SearchResults = $SearchResults[MetadataSchema::SCHEMAID_DEFAULT];
}

$TotalResults = count($SearchResults);

# and cut the results down to the desired amount
$SearchResults = array_slice($SearchResults, 0, $DesiredNumberOfResults, TRUE);

$GLOBALS["AF"]->LoadFunction("GetResourceSummaryForQuicksearch");
$ResourceData = array();
foreach ($SearchResults as $ResourceId => $Score)
{
    $Resource = new Resource($ResourceId);

    $HtmlData = GetResourceSummaryForQuicksearch($Resource);
    $HtmlData = QuickSearchHelper::HighlightSearchString($SearchString, $HtmlData);

    $ResourceData["X".$ResourceId] = $HtmlData;
}

# determine how many more results there are
$NumAdditionalResults = $TotalResults - count($ResourceData);

# convert into the format wanted by jquery-ui
$ResponseData = array();
foreach ($ResourceData as $Id => $Datum)
{
    $ResponseData[]= array(
        "label" => $Datum,
        "value" => $Datum,
        "ItemId" => $Id);
}

if ($NumAdditionalResults > 0)
{
    $ResponseData[]= array(
        "label" => "There ".($NumAdditionalResults>1 ? "are":"is")
           ." <b>".$NumAdditionalResults." additional result"
            .($NumAdditionalResults>1 ? "s": "")."</b> "
            ."<a class=\"cw-button cw-button-elegant\" "
            ."href=\"".OurBaseUrl()."index.php?P=SearchResults&amp;"
            .$SearchParams->UrlParameterString()."\">"
            ."View all</a>",
        "value" => "",
        "ItemId" => "");
}

print json_encode($ResponseData);
