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

# ----- 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)

/**
* Update assigned values from form.
* @param Resource $Resource Resource to update.
* @param MetadataField $Field Field to update.
*/
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 -----------------------------------------------------------------


# 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);  }

# make sure the user can modify this resource
if (!$G_Resource->UserCanModify($GLOBALS["G_User"]))
{
    DisplayUnauthorizedAccessPage();
    return;
}

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

# make sure it exists and then set the page title
if ($G_Field instanceof MetadataField)
{
    PageTitle("Assign ".$G_Field->GetDisplayName()."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);
    /**
    * Compare controlled names.
    * @param ControlledName $ResultA First name to compare
    * @param ControlledName $ResultB Second name to compare
    * @ return 1 if A is <= B, -1 otherwise.
    */
    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;
        }

        # grab all the matches, sort them, and pull out the chunk we want
        $ANames = $Factory->SearchForItemNames($G_SearchString, PHP_INT_MAX);
        asort($ANames);
        $ANames = array_slice( $ANames,
                               max(0, $G_Page-1)*$G_MaxNamesToDisplay,
                               $G_MaxNamesToDisplay,
                               TRUE);
    }
    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);
    }
}
