<!--                                                                  -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:include href="/app/tools/support/templates/layout.xsl" />

  <xsl:include href="/app/tools/common/production/templates/components/ui_file_uploader.xsl" />
  <xsl:include href="/app/tools/common/production/templates/components/button.xsl" />
  <xsl:include href="/app/tools/common/production/templates/components/icon.xsl" />

  <xsl:template name="mainBody" >
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"/>
    <script src="/production/javascript/jquery/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

    <xsl:call-template name="bodyTitle" >
      <xsl:with-param name="title">Data Imports</xsl:with-param>
    </xsl:call-template>

    <div id="importModal" class="import-modal">
      <div class="import-modal-content">
        <span class="import-close">
          <img src="/production/images/icons/16x16/close.gif"/>
        </span>
        <h2 id="import-modal-title">Data Template Upload</h2>
        <form id="importEdit" name="importEdit" action="/support/import" method="post" enctype="multipart/form-data">
          <input type="hidden" name="formSubmit" value="1" />
          <input id="import-modal-command" name="c" type="hidden" value="upload" />
          <input id="import-modal-action" name="action" type="hidden" value="" />
          <input id="import-modal-next-action" name="nextaction" type="hidden" value="" />
          <br/>

          <input type="hidden" name="filepath" id="import-modal-filepath" />
          <input type="hidden" name="ReturnTo" id="ReturnTo" value="{Params/ReturnTo}" />
          <input type="hidden" name="importID" id="import-modal-importid" value="" />
          <input type="hidden" name="fileID" id="import-modal-fileid" value="" />
          <div id="import-modal-clientcase" class="import-modal-clientcase">
          Client# <xsl:call-template name="displayClientSelector" />
<p/>
          Jira Case# <input type="text" name="caseno" id="import-modal-caseno" data-required="1" onblur="validateCase(this)"/><span id="import-modal-caseno-err"/>
          <p/>
          </div>
          <input id="import-modal-filename" name="filename" size="1" data-required="1" type="file" onblur="checkEmpty(this)"/>
          <span id="import-modal-filename-err"/>
          <span id="import-modal-filename-type"/>
          <br/>
          <input id="import-modal-analyze-button" type="button" value="Analyze File" />
<xsl:comment> Moved to confirmModal
          <input id="import-modal-submit-button" type="button" value="Upload File" />
</xsl:comment>
        </form>
      </div>
    </div>

    <div id="confirmModal" class="import-modal">
      <div class="import-modal-content">
        <span class="import-close">
          <img src="/production/images/icons/16x16/close.gif"/>
        </span>
        <h2 id="confirm-modal-title">Confirm <xsl:value-of select="/Root/ModalData/service"/> Template Import</h2>
<xsl:comment>
<h3>Client: <xsl:value-of select="/Root/ModalData/client_name"/> (ClientID <xsl:value-of select="/Root/ModalData/clientid"/>)</h3>
<h3>Case Number: <xsl:value-of select="/Root/ModalData/caseno"/></h3>
<h3>Filepath: <xsl:value-of select="/Root/ModalData/filepath"/></h3>
<h3>Template: <xsl:value-of select="/Root/ModalData/filename"/></h3>
<h3>Template Type: <xsl:value-of select="/Root/ModalData/service"/></h3>
</xsl:comment>
<p/>
<div style="width: 50%">
  The <xsl:value-of select="/Root/ModalData/service"/> template named
  <span style="background-color:yellow;"><xsl:value-of select="/Root/ModalData/filename"/></span> will be imported as part of
  case number <xsl:value-of select="/Root/ModalData/caseno"/> for client
  <xsl:value-of select="/Root/ModalData/client_name"/> (clientID <xsl:value-of select="/Root/ModalData/clientID"/>).
<p/>
<h3>Is the above information correct?</h3>
</div>
        <form id="confirmForm" name="confirmForm" action="/support/import" method="post" enctype="multipart/form-data">
          <input type="hidden" name="formSubmit" value="1" />
          <input type="hidden" id="confirm-modal-command" name="c" value="upload" />
          <input type="hidden" id="confirm-modal-action" name="action" value="{ModalData/action}" />
          <br/>
          <input type="hidden" name="filepath" id="confirm-modal-filepath" value="{/Root/ModalData/filepath}"/>
          <input type="hidden" name="ReturnTo" id="ReturnTo" value="{Params/ReturnTo}" />
          <input type="hidden" name="serviceID" id="confirm-modal-serviceid" value="{/Root/ModalData/serviceID}" />
          <input type="hidden" name="versionNum" id="confirm-modal-versionnum" value="{/Root/ModalData/versionNum}" />
          <input type="hidden" name="importID" id="confirm-modal-importid" value="{/Root/ModalData/importID}" />
          <input type="hidden" name="fileID" id="confirm-modal-fileid" value="{/Root/ModalData/fileID}" />

          <input type="hidden" name="clientid" id="confirm-modal-clientid" value="{ModalData/clientID}" />
          <input type="hidden" name="caseno" id="confirm-modal-caseno" value="{ModalData/caseno}" />

          <input type="hidden" id="import-modal-filename" name="filename" size="1" data-required="1"/>

          <input id="confirm-modal-submit-button" type="button" value="Yes, the above is correct" />
          <span class="import-close">
            <input id="confirm-modal-cancel-button" type="button" value="No, cancel the import" />
          </span>
        </form>
      </div>
    </div><!-- confirmModal -->

    <div id="errorModal" class="import-modal">
      <xsl:variable name="err"><xsl:value-of select="/Root/Collection/analyze_error"/></xsl:variable>

      <div class="import-modal-content">
        <span class="import-close">
          <img src="/production/images/icons/16x16/close.gif"/>
        </span>

        <xsl:if test="$err != ''">
          <h3>
          Error: <span style="color: red"><xsl:value-of select="$err"/></span>
          </h3>
        </xsl:if>

        <h2 id="confirm-modal-title">Unable to add file to <xsl:value-of select="/Root/ModalData/caseno"/></h2>
<p/>
<div style="width: 50%">
  The <xsl:value-of select="/Root/ModalData/service"/> template named
  <span style="background-color:yellow;"><xsl:value-of select="/Root/ModalData/filename"/></span>
  is the wrong type of template; expected <xsl:value-of select="/Root/ModalData/parent_service"/>.
<p/>
</div>
<button onclick="return docmd('add_import','{/Root/ModalData/importID}','{/Root/ModalData/caseno}','{/Root/ModalData/clientID}');">Ok</button>
      </div>
    </div><!-- confirmModal -->


    <xsl:comment>
      <xsl:choose>
        <xsl:when test="not(/Root/Params/action)">
           <p>No action detected!!!</p>
          <xsl:call-template name="importLayout" />

        </xsl:when>
        <xsl:otherwise>
          <xsl:call-template name="importList" />
        </xsl:otherwise>
      </xsl:choose>
    </xsl:comment>

    <xsl:call-template name="importLayout" />

    <script>

    $('#import_tree').on("changed.jstree", function(e, data) {
      console.log("D: data.selected = "+data.selected);
    })

    // Create the .jstree object
    .jstree();

    // handler for import modal close button
    $('.import-close').on('click', function(e) {
        $("#import-modal-caseno").attr('value','');
        $("#import-modal-filename").val('');
        $("#importModal").hide();
        $("#confirmModal").hide();
        $("#errorModal").hide();
    });

	<xsl:choose>
	  <xsl:when test="/Root/Params/action = 'analyze'">
         $("#importModal").hide();
         $("#errorModal").hide();

         <xsl:choose>
           <xsl:when test="/Root/Collection/errstr != ''">
             $("#confirmModal").hide();
             //$("#errorModal").show();
           </xsl:when>
           <xsl:when test="/Root/Collection/analyze_error != ''">
             $("#errorModal").show();
             $("#confirmModal").hide();
           </xsl:when>
           <xsl:otherwise>
             $("#confirmModal").show();
             //$("#errorModal").hide();
           </xsl:otherwise>
         </xsl:choose>
	  </xsl:when>
	  <xsl:otherwise>
         $("#confirmModal").hide();
         $("#importModal").hide();
         $("#errorModal").hide();
	  </xsl:otherwise>
	</xsl:choose>


    // remove modal if user clicks anywhere outside of it
    window.addEventListener("click", function(e) {
        var d = $(e.target).closest('div');
        var cn = d.attr('class');

        // catch anything within the import-modal divs (these will
        // have 'import-modal' as their class prefix).
        var patt = /^import-modal-/;
        if ( patt.test( d.attr('class') ) ) {
           e.stopPropagation();
        }
        else {
           $("#importModal").hide();
           $("#confirmModal").hide();
           $("#errorModal").hide();
        }

    });

      $("#import-modal-analyze-button").on('click', function() {

        $("#import-modal-next-action").val( $("#import-modal-action").val() );
        $("#import-modal-action").val('analyze');

        // clear existing errors so we can re-check
        $("#importEdit input[data-required]").each(function() {
          $("#"+this.id+"-err").html('');
        });

        // are we missing any required fields?
        cansubmit=1;
        $("#importEdit input[data-required]").each(function() {
           val = this.value;
           if ( val === '' ) {
             // if field is missing, highlight field and output error message
             $("#"+this.id+"-err").html('<span style="color:red">required</span>');
             cansubmit=0;
           } else {
             // check if data present with error message
             emsg = $("#"+this.id+"-err").html();
             if ( emsg != '' &amp;&amp; emsg != 'ok' ) {
                alert("Warning: emsg = "+emsg);
                cansubmit=0;
             }
           }
        });

        filename = $("#import-modal-filename").val();
        if ( !cansubmit ) {
          alert("Please enter missing fields");
        } else {
          $("form#importEdit").submit();
        }
      });


      $("#import-modal-submit-button").on('click', function() {
        cansubmit=1;
        $("#importEdit input[data-required]").each(function() {
           val = this.value;
           if ( val === '' ) {
             // if field is missing, highlight field and output error message
             $("#"+this.id+"-err").html('<span style="color:red">required</span>');
             cansubmit=0;
           } else {
             // check if data present with error message
             emsg = $("#"+this.id+"-err").html();
             if ( emsg != '' &amp;&amp; emsg != 'ok' ) {
                alert("Warning: emsg = "+emsg);
                cansubmit=0;
             }
           }
        });
        if ( cansubmit ) {
           $("form#importEdit").submit();
        }
      });

      $("#confirm-modal-submit-button").on('click', function() {
           $("form#confirmForm").submit();
      });

      function checkEmpty(e) {
        id = $(e).attr('id');
        val = $(e).val();
        m_id = id + '-err';
        if ( !val ) {
          //alert("Field empty!!!");
        } else {
          $("#"+m_id+"-err").html('');
        }
      }

      function validateCase(e) {
        id = $(e).attr('id');
        m_id = id + '-err';
        caseno = $(e).val();

        url = "http://rstest.royaltyshare.com/support/import?caseno="+caseno+"&amp;action=validcase";

        /* we need to manually encode the query parameters and set content type for POST */
        $.ajax({
          type: "POST",
          url: "/support/import",
          data: "caseno="+caseno+"&amp;action=validcase",
          contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
          dataType: "json",
          success: function(data) {
            $('#'+m_id).html( data.msg );
            console.log("validcase msg("+ data.msg +") status("+ data.status +")" );
          },
          error: function(data) {
            console.log("validcase returned error");
          }

        });

        return false;
      }

      function resetForm() {
        // clear form errors
        $("#importEdit input[data-required]").each(function() {
          $("#"+this.id+"-err").html('');
        });
      }

      function docmd(c, f, arg2, arg3) {
        // kludge - stop jstree from receiving button event
        var e = window.event;
        // IE9 + Other Browsers
        if (e.stopPropagation) {
          e.stopPropagation();
        }
        // IE8 and Lower
        else {
          e.cancelBubble = true;
        }

        if ( c == 'new_import2' ) {
          $("#import-modal-title").html('Create New Import');
          $("#import-modal-clientcase").show(); // display the clientid and caseno fields
          $("#import-modal-action").attr('value','upload_new');
          $("#import-modal-caseno").attr('value','');
          resetForm();
          $("#importModal").show();
        } else if ( c == 'add_import' ) {
          $("#errorModal").hide();
          $("#import-modal-title").html('Add To Existing Import '+ arg2);
          $("#import-modal-command").attr('value','upload');
          $("#import-modal-caseno").attr('value',arg2);
          $("#import-modal-importid").attr('value', f);
          $("#import-modal-action").attr('value','add_new');
          resetForm();
          $("#import-modal-clientcase").hide(); // hide the clientid and caseno fields
          $("#importModal").show();
        } else if ( c == 'download' ) {
          $("#import-modal-command").attr('value','download');
          $("#import-modal-fileid").attr('value', f);
          $("form#importEdit").submit();
        } else if ( c == 'finish_import' ) {
          $("#import-modal-command").attr('value','finish');
          $("#import-modal-importid").attr('value', f);
          $("form#importEdit").submit();
        }

        return false;
      }
    </script>

  </xsl:template>

  <xsl:template name="importLayout">
<hr/>

<xsl:variable name="errstr"><xsl:value-of select="/Root/Collection/errstr"/></xsl:variable>

  <xsl:if test="$errstr != ''">
    <h3>
    Error:
     <span style="color: red"><xsl:value-of select="$errstr"/></span>
    </h3>
  </xsl:if>

<p>Data Imports
      <button onclick="javascript:location.href='/support/import?c='">Refresh</button>
</p>


<div id="import_tree">
  <ul>
    <li>
      <xsl:if test="/Root/Params/selected">
        <xsl:attribute name="class">jstree-open</xsl:attribute>
      </xsl:if>

      Active Imports
      <button onclick="return docmd('new_import2');">Start New Case</button>
      <xsl:call-template name="displayCaseNodes">
        <xsl:with-param name="node_type">active</xsl:with-param>
        <xsl:with-param name="node_path" select="/Root/Import/ActiveImportList"/>
      </xsl:call-template>
    </li>

    <li>Closed Imports
      <xsl:call-template name="displayCaseNodes">
        <xsl:with-param name="node_type">closed</xsl:with-param>
        <xsl:with-param name="node_path" select="/Root/Import/ClosedImportList"/>
      </xsl:call-template>
    </li>
  </ul>
</div>


  </xsl:template>

<xsl:template name="displayCaseNodes">
  <xsl:param name="node_type"/>
  <xsl:param name="node_path"/>

  <xsl:variable name="selected"><xsl:value-of select="/Root/Params/selected"/></xsl:variable>

  <xsl:comment>
    #
    # displayCaseNodes: outputs the top-level case nodes (these are the root directories for each case)
    # under the specified node_path.  The initial import along with the uploading of related exceptions
    # are all grouped under the same top-level case node.  The XML is structured as follows:
    #
    #    DataImport    // case node
    #      DataImportList
    #        DataImport  // subsequent related-import
    #           DataImportFile
    #           . . .
    #        DataImport  // subsequent related-import
    #           DataImportFile
    #           . . .
    #    DataImport    // case node
    #      DataImportList
    #        DataImport
    #        . . .
    #
  </xsl:comment>

  <xsl:comment><!-- Capitalize first letter of node type--></xsl:comment>
  <xsl:variable name="labelName">
    <xsl:call-template name="capitalize">
      <xsl:with-param name="text" select="$node_type"/>
    </xsl:call-template>
  </xsl:variable>

  <xsl:comment>
    #
    # Loop over the top-level DataImport nodes and output sub-nodes (if any)
    #
  </xsl:comment>
  <xsl:choose>
    <xsl:when test="count($node_path/DataImport) != 0">
      <ul>
        <xsl:for-each select="$node_path/DataImport">
          <li>
            <xsl:if test="$selected = CaseID">
              <xsl:attribute name="class">
                jstree-open
              </xsl:attribute>
            </xsl:if>

            <!--SELECTED(<xsl:value-of select="$selected"/>)
            CASEID(<xsl:value-of select="CaseID"/>)
            -->

            <xsl:value-of select="DisplayName"/> [import_id <xsl:value-of select="ImportID"/>]
            <xsl:if test="$node_type != 'closed'">
              <button onclick="return docmd('add_import','{ImportID}','{CaseID}','{ClientID}');">Add</button>
              <button onclick="return docmd('finish_import','{ImportID}');">Close</button>
            </xsl:if>
            <xsl:call-template name="displayChildNodes">
              <xsl:with-param name="node_type" select="$node_type"/>
            </xsl:call-template>
          </li>
        </xsl:for-each>
      </ul>
    </xsl:when>
    <xsl:otherwise>
      <ul>
        <li>No <xsl:copy-of select="$node_type"/> imports</li>
      </ul>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template><!-- displayCaseNodes -->


<xsl:template name="displayChildNodes">
  <xsl:param name="node_type"/>
  <xsl:comment>
    #
    # displayChildNodes outputs the child node(s) of the current path (assumed
    # be a case node).
    # Each child node represents a sub-directory under the main case directory,
    # and is where the actual importing of files is staged from.
    # Each child node can have one or more files in it, depending on whether or
    # not a file has been uploaded.  For example, once a file has been uploaded,
    # the child node will have an input file along with an exceptions file (behind
    # the scenes, the directory will contain other files but we're not exposing
    # them here).
    #
  </xsl:comment>
  <ul>

    <xsl:comment>
      # Loop over each child node (if any)
    </xsl:comment>
    <xsl:choose>
      <xsl:when test="count(DataImportList/DataImport) != 0" >

        <xsl:for-each select="DataImportList/DataImport">

            <xsl:call-template name="displayImportNode">
              <xsl:with-param name="node_type" select="$node_type"/>
            </xsl:call-template>
        </xsl:for-each>
      </xsl:when>
      <xsl:otherwise>
         <li>
           <xsl:attribute name="data-jstree">{"icon":"/production/images/icons/16x16/alert.gif"}</xsl:attribute>
         No import activity detected</li>
      </xsl:otherwise>
      </xsl:choose>
  </ul>
</xsl:template><!-- displayChildNodes -->

<xsl:template name="displayImportNode">
  <xsl:param name="node_type"/>
  <xsl:comment>
    # Displays the file(s) contained in the current node
  </xsl:comment>

  <li>
    <xsl:attribute name="data-jstree">{"icon":"/production/images/icons/16x16/folder.gif"}</xsl:attribute>
    <xsl:value-of select="DisplayName"/> <!-- [dataImportID <xsl:value-of select="ImportID"/>] -->
    <!-- NodeType(<xsl:value-of select="$node_type"/>) -->

    <xsl:choose>
      <xsl:when test="count(FileList/File) != 0">
        <ul>
          <xsl:for-each select="FileList/File">
            <li>
              <xsl:attribute name="data-jstree">{"icon":"/production/images/icons/16x16/file.gif"}</xsl:attribute>
              <xsl:call-template name="displayFileNode">
                <xsl:with-param name="node_type" select="$node_type"/>
              </xsl:call-template>
            </li>
          </xsl:for-each>
        </ul>
      </xsl:when>
      <xsl:otherwise>
        <ul>
          <li>
            <xsl:attribute name="data-jstree">{"icon":"/production/images/icons/16x16/alert.gif"}</xsl:attribute>
            No files found
          <xsl:if test="$node_type = 'active'">
            <button onclick="return docmd('upload_file','{ImportID}','{ClientID}');">Upload File</button>
          </xsl:if>
          </li>
        </ul>
      </xsl:otherwise>
    </xsl:choose>

  </li>
</xsl:template>

<xsl:template name="displayClientSelector">
  <xsl:param name="selected_client"/>
  <xsl:variable name="selectedClient">
    <xsl:choose>
      <xsl:when test="$selected_client = ''">
        <xsl:value-of select="/Root/User/ClientID"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$selected_client"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>>

  <SELECT name="clientid" id="clientid">
    <xsl:for-each select="Clients/Client">
      <option value="{ClientID}">
        <xsl:if test="ClientID = $selectedClient">
          <xsl:attribute name="SELECTED"/>
        </xsl:if>
        <xsl:value-of select="ClientName"/> (<xsl:value-of select="ClientID"/>)
      </option>
    </xsl:for-each>
  </SELECT>
</xsl:template>

<xsl:template name="displayFileNode">
  <xsl:param name="node_type"/>
  <xsl:variable name="totalExceptions"><xsl:value-of select="TotalExceptions"/></xsl:variable>
  <xsl:variable name="totalRows"><xsl:value-of select="Records"/></xsl:variable>
  <xsl:variable name="rowCount">
    <xsl:choose>
      <xsl:when test="$totalRows = ''">
      </xsl:when>
      <xsl:otherwise>
        / <xsl:value-of  select="$totalRows"/> Row<xsl:if test="$totalRows > 1">s</xsl:if>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>

  File <xsl:value-of select="FileName"/> (file_id <xsl:value-of select="FileID"/>)
  <xsl:choose>
    <xsl:when test="$node_type = 'active'">

      <xsl:if test="FileType = 1"><!-- import file -->
        <xsl:choose>
          <xsl:when test="Status = 0">
            <span style="font-style:italic;color:red">Import terminated.</span>
          </xsl:when>
          <xsl:when test="Status = 1">
            <span style="font-style:italic;color:red">Import pending - please refresh page to check status.</span>
          </xsl:when>
        </xsl:choose>
      </xsl:if>

      <xsl:if test="FileType = 2"><!-- exceptions file -->
        <xsl:choose>
          <xsl:when test="$totalExceptions > 0">(
            <xsl:value-of select="TotalExceptions"/> Exception<xsl:if test="$totalExceptions > 1">s</xsl:if>
            <xsl:value-of select="$rowCount"/>)
            <button onclick="return docmd('download','{FileID}');">Download</button>
          </xsl:when>
          <xsl:otherwise>
            No exceptions detected.
          </xsl:otherwise>
        </xsl:choose>
      </xsl:if>

    </xsl:when>
    <xsl:otherwise>
      (<xsl:value-of select="$node_type"/>)
    </xsl:otherwise>
  </xsl:choose>

</xsl:template>

<xsl:template name="capitalize">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="' '"/>

    <xsl:variable name="upper-case" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
    <xsl:variable name="lower-case" select="'abcdefghijklmnopqrstuvwxyz'"/>

    <xsl:variable name="word" select="substring-before(concat($text, $delimiter), $delimiter)" />
    <xsl:value-of select="translate(substring($word, 1, 1), $lower-case, $upper-case)"/>
    <xsl:value-of select="translate(substring($word, 2), $upper-case, $lower-case)"/>
    <xsl:if test="contains($text, $delimiter)">
        <xsl:value-of select="$delimiter"/>
        <!-- recursive call -->
        <xsl:call-template name="capitalize">
            <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

<xsl:template name="printNode">
  <span style="background-color: yellow"><b>[</b> <xsl:value-of select="local-name()"/> <b>]</b></span>
</xsl:template>

<xsl:template name="importList" >
  <xsl:call-template name="collectionList" >
    <xsl:with-param name="columns" >
      <Column align="left" field="ModuleID">Module ID</Column>
      <Column align="left" field="Name">Name</Column>
      <Column align="left" field="Slug">Area</Column>
      <Column align="left" field="DisplayOrder">Index</Column>
    </xsl:with-param>
    <xsl:with-param name="editCommand">module_detail</xsl:with-param>
    <xsl:with-param name="addCommand">module_detail</xsl:with-param>
    <xsl:with-param name="addButtonText">Add Module</xsl:with-param>
    <xsl:with-param name="keyField">ModuleID</xsl:with-param>
  </xsl:call-template>
</xsl:template>

</xsl:stylesheet>
