<?PHP
#
#   FILE:  EditComplete.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

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

function Rules_ModifyValueIfNecessary(&$Rule)
{
    global $G_Schema;

    $Field = $G_Schema->GetField($Rule["Conditions"]["FieldId"]);
    $Type = $Field->Type();

    switch ($Type)
    {
        case MetadataSchema::MDFTYPE_TREE:
        case MetadataSchema::MDFTYPE_CONTROLLEDNAME:
        case MetadataSchema::MDFTYPE_OPTION:
            $InterfaceToggleThreshold = 45;
            $ValueCount = $Field->GetCountOfPossibleValues();

            # label for value given
            if ($ValueCount > 45)
            {
                $Factory = $Field->GetFactory();
                $Value = $Rule["Conditions"]["Value"];
                $Item = $Factory->GetItemByName($Value);

                # valid item
                if ($Item)
                {
                    $Rule["Conditions"]["Value"] = $Item->Id();
                }
            }
            break;

        case MetadataSchema::MDFTYPE_USER:
            $InterfaceToggleThreshold = 45;
            $ValueCount = $Field->GetCountOfPossibleValues();

            # label for value given
            if ($ValueCount > 45)
            {
                $Factory = new CWUserFactory();
                $Value = $Rule["Conditions"]["Value"];
                $Items = $Factory->FindUsers($Value);

                # valid item
                if (count($Items))
                {
                    $Item = array_shift($Items);
                    $Rule["Conditions"]["Value"] = $Item->Id();
                }
            }
            break;
    }
}

function Rules_ModifyBasedOnOperator(&$Rule)
{
    global $G_Schema;

    $OperatorMap = Rules_GetOperatorMap();
    $MappedOperator = $OperatorMap[$Rule["Conditions"]["Operator"]];
    $Value = $Rule["Conditions"]["Operator"];

    # if the operator doesn't need a condition or is not supported or
    # operator needs a value, but one wasn't given so revert to no conditions
    if (is_null($MappedOperator) || !$Value)
    {
       $Rule["Conditions"]["Operator"] = NULL;
       $Rule["Conditions"]["Value"] = NULL;
       return;
    }

    $Field = $G_Schema->GetField($Rule["Conditions"]["FieldId"]);
    $Type = $Field->Type();

    switch ($Type)
    {
        case MetadataSchema::MDFTYPE_NUMBER:
        case MetadataSchema::MDFTYPE_DATE:
        case MetadataSchema::MDFTYPE_TIMESTAMP:
        case MetadataSchema::MDFTYPE_TREE:
        case MetadataSchema::MDFTYPE_CONTROLLEDNAME:
        case MetadataSchema::MDFTYPE_OPTION:
        case MetadataSchema::MDFTYPE_USER:
            # just use the correct operator
            $Rule["Conditions"]["Operator"] = $MappedOperator;
            break;

        case MetadataSchema::MDFTYPE_FLAG:
            # use the correct operator and value
            $Rule["Conditions"]["Operator"] = $MappedOperator;
            $Rule["Conditions"]["Value"] = $Value == 8 ? "1" : "0";
            break;
    }
}

function Rules_ModifyActionIfNecessary(&$Rule)
{
    if ($Rule["Actions"]["UserIsField"])
    {
        unset($Rule["Actions"]["UserPrivilegeRestrictions"]);
    }

    else
    {
        unset($Rule["Actions"]["UserIsField"]);
    }
}

function Rules_GetOperatorMap()
{
    return array(
        # has changed
        1 => NULL,
        # equals
        2 => "=",
        # does not equal
        3 => "!=",
        # is less than
        4 => "<",
        # is greater than
        5 => ">",
        # is less than or equal to
        6 => "<=",
        # is greater than or equal to
        7 => ">=",
        # set to true
        8 => "=",
        # set to false
        9 => "=",
        # is changed to (controlled value)
        10 => "=",
        # is changed to (user value)
        11 => "=",
        # is changed to user with privilege
        12 => NULL,
        # file added
        13 => NULL);
}

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

# check that user should be on this page
CheckAuthorization(PRIV_COLLECTIONADMIN, PRIV_SYSADMIN);

$AF->SuppressHTMLOutput();

global $G_Schema;
global $G_RulesPlugin;

$G_Schema = new MetadataSchema();
$G_RulesPlugin = $G_PluginManager->GetPlugin("Rules");

$Submit = GetArrayValue($_POST, "F_Submit");

# remove the rule if requested and go back to the list
if ($Submit == "Remove Rule")
{
    $RuleId = GetArrayValue($_POST, "F_RuleId");
    $G_RulesPlugin->DeleteRule($RuleId);

    $AF->SetJumpToPage("P_Rules_List");
    return;
}

# just go back to the list
else if ($Submit == "Cancel")
{
    $AF->SetJumpToPage("P_Rules_List");
    return;
}

$RequiredValues = array(
    "FieldId",
    "Enabled",
    "Operator",
    "Type",
    "UserPrivilegeRestrictions",
    "UserIsField",
    "TemplateId");
$OtherValues = array(
    "RuleId",
    "Value");

foreach ($RequiredValues as $RequiredValue)
{
    # $FieldId, $Enabled, $Operator, $Type, $UserPrivilegeRestrictions,
    # $UserIsField, $TemplateId
    $$RequiredValue = GetArrayValue($_POST, "F_".$RequiredValue);

    # if not set
    if (is_null($$RequiredValue))
    {
        $AF->SetJumpToPage("F_Rules_List");
        return;
    }
}

foreach ($OtherValues as $OtherValue)
{
    # $RuleId, $Value
    $$OtherValue = GetArrayValue($_POST, "F_".$OtherValue);
}

# get user privilege restrictions in the form necessary
$UserPrivilegeRestrictions = $UserPrivilegeRestrictions == 0
    ? array() : array($UserPrivilegeRestrictions);

# construct the rule from the values
$Rule = array(
    "Enabled" => $Enabled,
    "Conditions" => array(
        "FieldId" => $FieldId,
        "Operator" => $Operator,
        "Value" => $Value),
    "Actions" => array(
        "Type" => $Type,
        "UserPrivilegeRestrictions" => $UserPrivilegeRestrictions,
        "UserIsField" => $UserIsField,
        "TemplateId" => $TemplateId));

# existing rule
if ($RuleId)
{
    # set the ID
    $Rule["RuleId"] = $RuleId;
}

# new rule
else
{
    # add new rule and set the ID
    $NewRule = $G_RulesPlugin->AddNewRule();
    $Rule["RuleId"] = $NewRule["RuleId"];
}

# modify rule if necessary
Rules_ModifyValueIfNecessary($Rule);
Rules_ModifyBasedOnOperator($Rule);
Rules_ModifyActionIfNecessary($Rule);

# update the rule
$G_RulesPlugin->UpdateRule($Rule);

# go back to the list
$AF->SetJumpToPage("P_Rules_List");
