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

/**
*
*/
class REFormatXml extends Plugin {

    # ---- STANDARD PLUGIN INTERFACE -----------------------------------------

    /**
    * Set plugin attributes.
    */
    function Register()
    {
        $this->Name = "Resource Export Format: XML";
        $this->Version = "1.0.0";
        $this->Description = "";
        $this->Author = "Internet Scout";
        $this->Url = "http://scout.wisc.edu/cwis/";
        $this->Email = "scout@scout.wisc.edu";
        $this->Requires = array(
                "CWISCore" => "3.0.0",
                "ResourceExporter" => "1.0.0");
        $this->EnabledByDefault = TRUE;
    }

    /**
    * Initialize the plugin.  This is called (if the plugin is enabled) after
    * all plugins have been loaded but before any methods for this plugin
    * (other than Register()) have been called.
    * @return NULL if initialization was successful, otherwise a string containing
    *       an error message indicating why initialization failed.
    */
    function Initialize()
    {
        $ExportedDataTypes = array(
                MetadataSchema::MDFTYPE_TEXT,
                MetadataSchema::MDFTYPE_PARAGRAPH,
                MetadataSchema::MDFTYPE_NUMBER,
                MetadataSchema::MDFTYPE_TIMESTAMP,
                MetadataSchema::MDFTYPE_URL,
                MetadataSchema::MDFTYPE_DATE,
                MetadataSchema::MDFTYPE_FLAG,
                MetadataSchema::MDFTYPE_TREE,
                MetadataSchema::MDFTYPE_CONTROLLEDNAME,
                MetadataSchema::MDFTYPE_OPTION,
                MetadataSchema::MDFTYPE_POINT,
                MetadataSchema::MDFTYPE_USER,
                );
        $GLOBALS["G_PluginManager"]->GetPlugin("ResourceExporter")->
                RegisterFormat("XML", "xml", array($this, "Export"),
                $ExportedDataTypes);
        return NULL;
    }


    # ---- HOOKED METHODS ----------------------------------------------------

    /**
    * HOOKED METHOD:
    */


    # ---- CALLABLE METHODS --------------------------------------------------

    /**
    * Export resource metadata to XML format.
    * @param array $ResourceIds Array of Resource IDs.
    * @param array $FieldIds Array of IDs of metadata fields to export.
    *       (NULL to export all enabled fields)
    * @param string $FileName Name of file to export to with leading path.
    * @param array $ParamSettings Settings for any export parameters, with
    *       parameter names for the array index and parameter settings for
    *       the array values.
    * @return int Number of resources exported, or NULL if export failed.
    */
    function Export($ResourceIds, $FieldIds, $FileName, $ParamSettings)
    {
        # start XML output
        $Out = new XMLWriter();
        touch($FileName);
        $Out->openURI($FileName);
        $Out->setIndent(TRUE);
        $Out->setIndentString("    ");
        $Out->startDocument("1.0", "UTF-8");
        $Out->startElement("ResourceCollection");

        # for each resource
        $Schema = new MetadataSchema();
        $Fields = $Schema->GetFields(NULL, MetadataSchema::MDFORDER_EDITING);
        $ExportedResourceCount = 0;
        foreach ($ResourceIds as $ResourceId)
        {
            # load resource
            $Resource = new Resource($ResourceId);

            # start new resource entry
            $Out->startElement("Resource");

            # for each metadata field
            foreach ($Fields as $Field)
            {
                # if field is enabled
                if ($Field->Enabled()
                        && (($FieldIds == NULL)
                                || in_array($Field->Id(), $FieldIds)))
                {
                    # if field has content
                    $Value = $Resource->Get($Field, TRUE);
                    if ((is_array($Value) && count($Value))
                            || (!is_array($Value) && ($Value !== NULL)))
                    {
                        # handle output of field based on field type
                        switch ($Field->Type())
                        {
                            case MetadataSchema::MDFTYPE_TEXT:
                            case MetadataSchema::MDFTYPE_PARAGRAPH:
                            case MetadataSchema::MDFTYPE_NUMBER:
                            case MetadataSchema::MDFTYPE_TIMESTAMP:
                            case MetadataSchema::MDFTYPE_URL:
                                if (strlen($Value))
                                {
                                    $Out->writeElement($Field->DBFieldName(), $Value);
                                }
                                break;

                            case MetadataSchema::MDFTYPE_DATE:
                                if (strlen($Value->Formatted()))
                                {
                                    $Out->writeElement($Field->DBFieldName(),
                                            $Value->Formatted());
                                }
                                break;

                            case MetadataSchema::MDFTYPE_FLAG:
                                $Out->writeElement($Field->DBFieldName(),
                                        ($Value ? "TRUE" : "FALSE"));
                                break;

                            case MetadataSchema::MDFTYPE_TREE:
                            case MetadataSchema::MDFTYPE_CONTROLLEDNAME:
                            case MetadataSchema::MDFTYPE_OPTION:
                                foreach ($Value as $Item)
                                {
                                    $Out->writeElement($Field->DBFieldName(),
                                            $Item->Name());
                                }
                                break;

                            case MetadataSchema::MDFTYPE_POINT:
                                $Out->writeElement($Field->DBFieldName(),
                                        $Value["X"].",".$Value["Y"]);
                                break;

                            case MetadataSchema::MDFTYPE_USER:
                                if (strlen($Value->Get("UserName")))
                                {
                                    $Out->writeElement($Field->DBFieldName(),
                                            $Value->Get("UserName"));
                                }
                                break;

                            default:
                                throw new Exception(
                                        "Export of unsupported metadata field type ("
                                        .MetadataSchema::GetConstantName(
                                                $Field->Type(), "MDFTYPE")
                                        .") requested.");
                                break;
                        }
                    }
                }
            }

            # end resource entry
            $Out->endElement();
            $ExportedResourceCount++;
        }

        # end XML output
        $Out->endDocument();

        # return number of exported resources to caller
        return $ExportedResourceCount;
    }


    # ---- PRIVATE INTERFACE -------------------------------------------------

}

