<?PHP
#
#   FILE:  EditResourceSearchName.php
#
#   FUNCTIONS PROVIDED:
#       FunctionName($Parameter, $Parameter)
#           - brief description of function supplied for use in HTML file
#
#   FUNCTIONS EXPECTED:
#       FunctionName($Parameter, $Parameter)
#           - brief description of function that HTML file must supply
#
#   OPTIONAL FUNCTIONS:
#       FunctionName($Parameter, $Parameter)
#           - brief description of function that HTML file may supply
#
#   FORM FIELDS EXPECTED:
#       F_FormFieldName
#           - brief description of form field purpose and/or content
#
#   Part of the Scout Portal Toolkit
#   Copyright 2006 Internet Scout Project
#   http://scout.wisc.edu
#

# ----- CONFIGURATION  -------------------------------------------------------

# maximum number of names to display
$G_MaxNamesToDisplay = 200;

# ----- EXPORTED FUNCTIONS ---------------------------------------------------
# (functions intended for use in corresponding HTML file)

# ----- LOCAL FUNCTIONS ------------------------------------------------------
# (functions intended for use only within this file)

# use form values to update values assigned to field
function UpdateAssignments($Resource, $Field)
{
    # clear all existing assignments
    $Resource->ClearByField($Field);

    # for each possible field value
    $NumberOfValues = $_POST["H_HighestNameIndex"];
    for ($Index = 0;  $Index < $NumberOfValues;  $Index++)
    {
        # if value is set
        if (isset($_POST["F_Names_".$Index]))
        {
            $Resource->Set($Field, $_POST["F_Names_".$Index]);
        }
    }
}

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

# PrintForDebug("POST", $_POST);
if (!CheckAuthorization(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN)) {  return;  }

# retrieve resource being edited
if (isset($_GET["ID"])) {  $ResourceId = $_GET["ID"];  }
elseif (isset($_POST["H_ResourceId"])) {  $ResourceId = $_POST["H_ResourceId"];  }
if (isset($ResourceId)) {  $G_Resource = new Resource($ResourceId);  }

# retrieve field to search
if (isset($_GET["MF"])) {  $FieldId = $_GET["MF"];  }
elseif (isset($_POST["H_FieldId"])) {  $FieldId = $_POST["H_FieldId"];  }
if (isset($FieldId))
{
    $Schema = new MetadataSchema();
    $G_Field = $Schema->GetField($FieldId);
}

# make sure it exists and then set the page title
if ($G_Field instanceof MetadataField)
{
    PageTitle("Assign ".$G_Field->Name()."s");
}

# if we have a resource and a field of the correct type
if (isset($G_Resource) && ($G_Resource->Status() == 1)
        && isset($G_Field) && ($G_Field->Status() == MetadataSchema::MDFSTAT_OK)
        && (($G_Field->Type() == MetadataSchema::MDFTYPE_TREE)
                || ($G_Field->Type() == MetadataSchema::MDFTYPE_CONTROLLEDNAME)))
{
    # take action based on which submit button was pressed (if any)
    if (isset($_POST["Submit"]))
    {
        switch ($_POST["Submit"])
        {
            case ">":
            case "<":
            case ">>":
            case "<<":
            case ">|":
            case "|<":
                # save new assignment values
                UpdateAssignments($G_Resource, $G_Field);
                break;

            case "Assign":
                # save new assignment values
                UpdateAssignments($G_Resource, $G_Field);

                # return to resource editing page
                $AF->SetJumpToPage("EditResource&ID=".$G_Resource->Id());
                return;
                break;

            case "Search":
                # save new assignment values
                UpdateAssignments($G_Resource, $G_Field);
                break;

            case "Add":
                # if new controlled name was supplied
                if (isset($_POST["F_NewName"])
                        && strlen(trim($_POST["F_NewName"])))
                {
                    # add new controlled name
                    $VariantName = isset($_POST["F_NewVariant"])
                            ? $_POST["F_NewVariant"] : NULL;
                    $QualifierId = (!isset($_POST["F_NewQualifier"])
                            || $_POST["F_NewQualifier"] == "--")
                            ? "NULL" : intval($_POST["F_NewQualifier"]);
                    $NewControlledName = new ControlledName(NULL,
                            $_POST["F_NewName"], $G_Field->Id(),
                            $QualifierId, $VariantName);

                    # assign new name to resource
                    $G_Resource->Set($G_Field, $NewControlledName->Id());
                }
                break;

            default:
                break;
        }
    }
    elseif (isset($_POST["ExtraSubmit"]))
    {
        switch ($_POST["ExtraSubmit"])
        {
            case "Search":
                # save new assignment values
                UpdateAssignments($G_Resource, $G_Field);

                # make sure second search value gets used if available
                if (isset($_POST["F_SearchStringTwo"])
                    && strlen(trim($_POST["F_SearchStringTwo"])))
                {
                    unset($_POST["F_SearchStringOne"]);
                }
                break;
        }
    }

    # retrieve currently selected values for field
    $G_CurrentNames = $G_Resource->GetByField($G_Field, TRUE);
    $CNames = $G_Resource->GetByField($G_Field);
    asort($G_CurrentNames);
    function ControlledNameCompare($ResultA, $ResultB)
    {
        return ($ResultA->Name() <= $ResultB->Name()) ? 1 : -1;
    }
    uasort($G_CurrentNames, "ControlledNameCompare");

    # retrieve item factory for field
    $Factory = $G_Field->GetFactory();

    # page info
    if (isset($_POST["Submit"]) && $_POST["Submit"] == "Search"
        || !isset($_POST["H_Page"]))
    {
        $G_Page = 1;
    }

    else
    {
        $G_Page = intval($_POST["H_Page"]);
    }

    # if search string was supplied
    if ((isset($_POST["F_SearchStringOne"])
                    && strlen(trim($_POST["F_SearchStringOne"])))
            || (isset($_POST["F_SearchStringTwo"])
                    && strlen(trim($_POST["F_SearchStringTwo"]))))
    {
        # search for field values that match string
        $G_SearchString = (isset($_POST["F_SearchStringOne"])
                        && strlen(trim($_POST["F_SearchStringOne"])))
                ? $_POST["F_SearchStringOne"] : $_POST["F_SearchStringTwo"];
        $G_SearchString = trim($G_SearchString);
        $G_AvailableNamesTotal = $Factory->GetCountForItemNames($G_SearchString,
                FALSE, TRUE);
        $G_MaxPages = ceil($G_AvailableNamesTotal/$G_MaxNamesToDisplay);

        # moving left or right
        if (isset($_POST["Submit"]))
        {
            switch($_POST["Submit"])
            {
                case ">":
                    $G_Page++; break;
                case "<":
                    $G_Page--; break;
                case ">>":
                    $G_Page += ceil($G_MaxPages/5); break;
                case "<<":
                    $G_Page -= ceil($G_MaxPages/5); break;
                case ">|":
                    $G_Page = $G_MaxPages; break;
                case "|<":
                    $G_Page = 1; break;
            }
        }

        # negative page number
        if ($G_Page < 1)
        {
            $G_Page = 1;
        }

        # page number too large
        else if ($G_Page > $G_MaxPages)
        {
            $G_Page = $G_MaxPages;
        }

        $ANames = $Factory->SearchForItemNames($G_SearchString,
                $G_MaxNamesToDisplay, FALSE, TRUE, abs($G_Page-1)*$G_MaxNamesToDisplay);
    }
    else
    {
        $G_AvailableNamesTotal = intval($G_Field->GetCountOfPossibleValues());
        $G_MaxPages = ceil($G_AvailableNamesTotal/$G_MaxNamesToDisplay);

        # moving left or right
        if (isset($_POST["Submit"]))
        {
            switch($_POST["Submit"])
            {
                case ">":
                    $G_Page++; break;
                case "<":
                    $G_Page--; break;
                case ">>":
                    $G_Page += ceil($G_MaxPages/5); break;
                case "<<":
                    $G_Page -= ceil($G_MaxPages/5); break;
                case ">|":
                    $G_Page = $G_MaxPages; break;
                case "|<":
                    $G_Page = 1; break;
            }
        }

        # negative page number
        if ($G_Page < 1)
        {
            $G_Page = 1;
        }

        # page number too large
        else if ($G_Page > $G_MaxPages)
        {
            $G_Page = $G_MaxPages;
        }

        # retrieve the first block of field values
        $ANames = $G_Field->GetPossibleValues($G_MaxNamesToDisplay,
            abs($G_Page-1)*$G_MaxNamesToDisplay);
        $G_SearchString = "";
    }

    # remove currently selected values from available values
    $ANames = array_diff_assoc($ANames, $CNames);

    # retrieve controlled name objects
    asort($ANames);
    $G_AvailableNames = array();
    foreach ($ANames as $Id => $Name)
    {
        $G_AvailableNames[$Id] = $Factory->GetItem($Id);
    }
}
