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

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

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

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

/**
* Retrieve list of available folders of resources to export.
* @return array Array with Folder names for the values and Folder IDs for
*       the index, plus an entry for all resources with -1 as the index.
*/
function GetAvailableSources()
{
    # start with empty list of sources
    $Sources = array();

    # if Folders plugin is available
    if ($GLOBALS["G_PluginManager"]->PluginEnabled("Folders"))
    {
        # retrieve folders
        $Folders = array();
        $FFactory = new Folders_FolderFactory($GLOBALS["G_User"]->Id());
        $ResourceFolder = $FFactory->GetResourceFolder();
        $FolderIds = $ResourceFolder->GetItemIds();
        foreach ($FolderIds as $Id)
        {
            $Folders[$Id] = new Folder($Id);
        }

        # assemble source list from folder names
        foreach ($Folders as $Id => $Folder)
        {
            $Sources[$Id] = $Folder->Name()." (".$Folder->GetItemCount()." resource"
                    .(($Folder->GetItemCount() == 1) ? "" : "s").")";
        }

        # add option list selection for all resources
        $Sources[-1] = "ALL RESOURCES";
    }

    # return sources to caller
    return $Sources;
}

/**
* Retrieve list of resource folders that should not be used for export.
* @param array $AvailableSources Available folders of resources to export.
* @return array Array with Folder names for the values and Folder IDs
*       for the index.
*/
function GetDisabledSources($AvailableSources)
{
    # start out assuming no sources will be disabled
    $DisabledSources = array();

    # for each available source
    foreach ($AvailableSources as $Id => $SourceName)
    {
        # if source is a folder
        if ($Id >= 0)
        {
            # if folder has no resources
            $Folder = new Folder($Id);
            if ($Folder->GetItemCount() == 0)
            {
                # add source to disabled list
                $DisabledSources[$Id] = $SourceName;
            }
        }
    }

    # return list of disabled sources to caller
    return $DisabledSources;
}


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

if (!CheckAuthorization(PRIV_COLLECTIONADMIN)) {  return;  }

$Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
$Schema = new MetadataSchema(MetadataSchema::SCHEMAID_DEFAULT);
$UserId = $GLOBALS["G_User"]->Id();
$H_ErrorList = new ErrorList();

# determine which action we are currently taking
if (GetFormValue("F_Submit") == "Cancel")
{
    $GLOBALS["AF"]->SetJumpToPage("SysAdmin");
    return;
}
elseif (GetFormValue("F_Submit") == "Export")
{
    $H_Action = "EXPORT";
}
else
{
    $H_Action = "SETUP";
}

# if we are at the data export stage
if ($H_Action == "EXPORT")
{
    # retrieve ID of folder with resources to be exported
    $SourceFolderId = (isset($_POST["F_ResourceSource"])
                    && ($_POST["F_ResourceSource"] >= 0))
            ? $_POST["F_ResourceSource"] : NULL;

    # retrieve and check list of metadata fields to export
    $FieldIds = NULL;
    $Fields = $Schema->GetFields();
    foreach ($Fields as $Field)
    {
        if (array_key_exists("F_ExportField_".$Field->Id(), $_POST))
        {
            $FieldIds[] = $Field->Id();
        }
    }
    if ($FieldIds === NULL)
    {
        $H_ErrorList->AddMessage(
                "No metadata fields were selected for export.",
                "F_ExportField_");
    }
    else
    {
        $IdLists = $Plugin->ConfigSetting("SelectedFieldIdLists");
        $IdLists[$UserId] = $FieldIds;
        $Plugin->ConfigSetting("SelectedFieldIdLists", $IdLists);
    }

    # retrieve and check export format
    $Format = $_POST["F_Format"];
    if (!$Plugin->IsRegisteredFormat($Format))
    {
        $H_ErrorList->AddMessage(
                "Export format was not recognized.",
                "F_Format");
    }
    else
    {
        $Formats = $Plugin->ConfigSetting("SelectedFormats");
        $Formats[$UserId] = $Format;
        $Plugin->ConfigSetting("SelectedFormats", $Formats);
    }

    # retrieve and save export format parameters
    $Formats = $Plugin->GetFormats();
    $FormatParameters = $Plugin->GetExportParameters();
    $FormatParameterValues = $Plugin->ConfigSetting("FormatParameterValues");
    foreach ($FormatParameters as $FormatName => $FormatParams)
    {
        if (count($FormatParams))
        {
            if (!array_key_exists($FormatName, $FormatParameterValues))
                    {  $FormatParameterValues[$FormatName] = array();  }
            $CfgUI = new ConfigSettingsUI($FormatParams,
                    $FormatParameterValues[$FormatName], $FormatName);
            $FormatParameterValues[$FormatName] = $CfgUI->GetNewSettingsFromForm();
        }
    }
    $Plugin->ConfigSetting("FormatParameterValues", $FormatParameterValues);

    # if errors were found
    if ($H_ErrorList->HasErrors())
    {
        # switch to setup mode
        $H_Action = "SETUP";
    }
    else
    {
        # export data
        $H_ExportedResourceCount = $Plugin->ExportData(
                $Format, $SourceFolderId, $FieldIds,
                isset($FormatParameterValues[$Format])
                        ? $FormatParameterValues[$Format]
                        : array());

        # if export succeeded
        if ($H_ExportedResourceCount !== NULL)
        {
            # set values for display in HTML
            $H_ExportedFileName = $Plugin->LastExportFileName();
            $H_ExportedFileSecret = $Plugin->LastExportFileSecret();
        }
        else
        {
            # retrieve error messages
            $Errors = $Plugin->LastExportErrorMessages();
            foreach ($Errors as $ErrMsg)
            {
                $H_ErrorList->AddMessage($ErrMsg);
            }

            # switch to setup mode
            $H_Action = "SETUP";
        }
    }
}

# if we are at the export setup stage
if ($H_Action == "SETUP")
{
    $H_AvailableSources = GetAvailableSources();
    $H_DisabledSources = GetDisabledSources($H_AvailableSources);

    # if folders is enabled, use the current user's selected folder
    # otherwise use the first available source
    if ($GLOBALS["G_PluginManager"]->PluginEnabled("Folders"))
    {
        $FFactory = new Folders_FolderFactory($GLOBALS["G_User"]->Id());
        $H_SelectedSource = $FFactory->GetSelectedFolder()->Id();
    }
    else
    {
        $PossibleValueIds = array_keys($H_AvailableSources);
        $H_SelectedSource = reset($PossibleValueIds);
    }

    # retrieve values for metadata field list
    $H_AvailableFields = $Schema->GetFields(
            NULL, MetadataSchema::MDFORDER_ALPHABETICAL);
    $IdLists = $Plugin->ConfigSetting("SelectedFieldIdLists");
    $H_SelectedFieldIds = (count($IdLists) && array_key_exists($UserId, $IdLists))
            ? $IdLists[$UserId] : array();
    $H_ExportedDataTypes = $Plugin->GetExportedDataTypes();

    # if no metadata fields selected
    if (!count($H_SelectedFieldIds))
    {
        # select standard fields
        $StandardFieldNames = array(
                "Title",
                "Description",
                "Url",
                );
        foreach ($StandardFieldNames as $Name)
        {
            $Id = $Schema->GetFieldIdByMappedName($Name);
            if ($Id !== NULL) {  $H_SelectedFieldIds[] = $Id;  }
        }
    }

    # retrieve values for format list
    $H_AvailableFormats = $Plugin->GetFormats();
    $SelectedFormats = $Plugin->ConfigSetting("SelectedFormats");
    $DefaultFormat = count($H_AvailableFormats) ? $H_AvailableFormats[0] : NULL;
    $H_SelectedFormat = (count($SelectedFormats)
            && array_key_exists($UserId, $SelectedFormats))
            ? $SelectedFormats[$UserId] : $DefaultFormat;
    $H_FormatParameters = $Plugin->GetExportParameters();
    $H_FormatParameterValues = $Plugin->ConfigSetting("FormatParameterValues");
}
