<?xml version="1.0" encoding="UTF-8"?>
<actions>

<meta>
  <description lang="de">Schnittstelle zum VuFind-System</description>
  <description lang="en">VuFind-System interface</description>
  <variable name="baseurl">
    <description lang="de">Internetadresse der Bibliothek (inklusive https:// Protokoll)</description>
    <description lang="en">URL of the library OPAC (starting with https://)</description>
  </variable>
  <variable name="loginParams">
    <description lang="de">Eventuell benötigte zusätzliche Parameter für den Login</description>
    <description lang="en">Optional parameters for login</description>
  </variable>
  
</meta>


<action id="connect">
  <s>accounturl := $baseurl || "/MyResearch/"</s>
</action>

<action id="internal-login"> 
  <if test="not(get('loggedIn', false()))">
    <page url="{$accounturl}/UserLogin"/>
    <pattern><form t:condition="(@id,@name)='loginForm'">
      {$form := form(., ({"username": $username, "password": $password}, get("loginParams",())[1]))}
    </form></pattern>
    <page url="{$form}"/>
    <pattern><body><div class="alert alert-danger">{
    string() ! (if (matches(., "Ungültige Login-?[aA]ngaben")) then vl:raise-login(.)
    else vl:raise(.))
    }</div>?</body></pattern>
    <s>loggedIn := true()</s>
  </if>
</action>

<action id="update-all">
  <call action="internal-login"/>
  <s>vl:delete-current-books(), inOrderings := false()</s>
  <page url="{$accounturl}/CheckedOut" templateFile="list"/>
  <s>inOrderings := true()</s>
  <page url="{$accounturl}/Holds" templateFile="list"/>
</action>

<action id="renew-list">
  <s>form := request-combine( $renew-form, $renew-books!{"renewSelectedIDS[]": .("_renewID")} )</s>
  <page url="{$form}"/>
  <call action="update-all"/>
</action>

<action id="cancel-list">
  <s>form := request-combine( $cancel-form, $cancel-books!{"cancelSelectedIDS[]": .("_cancelID")} )</s>
  <page url="{$form}"/>
  <call action="update-all"/>
</action>

<action id="search-connect">
  <call action="connect"/>
  <s>searchurl := $baseurl || "/Search/"</s>
  <!--possible: alternative, opensearch and append &view=rss but it lacks some info-->
  <page url="{$searchurl}/Advanced"/>
  <pattern>
    <form t:condition="contains(@action, 'Search/Results')">
      {$search-request := {"url": resolve-html(@action) || "?", "method": (@method, "GET")[1]},
       $daterange := (.//input[@name = "daterange[]"]/@value, "publishDate")[1],
       search-params := ("title", "author", "free", "keywords", "year", "isbn", 
         //select/(
           let $name := switch (@id)
             case 'limit_collection' case 'limit_mega_collection' return "libraryBranch"
             case 'limit_building' return "libraryLocation"
             case 'limit_format' return "mediaType"
             default return ()
           where $name
           return {"name": $name, "options": ({"caption": "Alle", "value": ""}, .//option)}
         )
       )
       }
    </form>
  </pattern>
</action>

<action id="search">
  <s>
    page := 1,
    search-keys := {"author": "Author", "title": "Title", "free": "AllFields", "keywords": "Subject", "isbn": "ISN"},
    search-filter-keys := ("libraryBranch", "libraryLocation", "mediaType"),
    search-next-page := request-combine($search-request, (
      "sort=relevance",
      "join=AND",
      {"bool0[]": "AND"},
      for $key in jn:keys($book) where $book($key) and $search-keys($key) return
        {"lookfor0[]": $book($key), "type0[]": $search-keys($key)},
      if (boolean($book.year)) then 
        if (contains($book.year, "-")) then 
          ({"daterange[]": $daterange}, {
            $daterange || "from": substring-before($book.year, "-"), 
            $daterange || "to": substring-after($book.year, "-") })
        else {"lookfor0[]": $book.year, "type0[]": "year"}
      else (),
      $search-filter-keys!$book(.)[.]!{"filter[]": .}
     ))
  </s>
  <call action="search-internal-vufind"/>
<!--  <s>book:={"title": "test", "holdings": {"libraryBranch":  "Lesesaal 3. Etage ", "_orderUrl": "/Record/003307385/Hold?id=003307385&item_id=DUE50003307385000010&hashKey=38685b4a112ecf8943b12c8660e2d3e5"}}</s>-->

</action>

<action id="search-next-page"> 
  <call action="search-internal-vufind"/>
</action>

<action id="search-internal-vufind">
  <page url="{$search-next-page}" templateFile="searchList"/>
  <if test="$singleMode">
    <page url="{$baseurl}/Record/{$singleModeRecordId}" templateFile="searchDetails" />
  </if>
  <else>
  <try>
    <s>item-statuses := (), params := join( $new-books/_recordId ! ("id%5B%5D="||.), $amp) </s>
    <json url="{$baseurl}/AJAX/JSON?method=getItemStatuses&{$params}"/>
    <s>
    let $data := $json?data
    return $item-statuses := typeswitch($data)
      case map(*) return $data?statuses?*
      default return $data?*
    </s>
    <catch errors="*"/>
  </try>
  <s>$page := $page + 1,
     for $b in $new-books 
     let $id := $b._recordId
     let $status := $item-statuses[id = $id][not(missing_data = true())][1]
     return $book := if (empty($status)) then $b else {| 
       $b, 
       $status!{"statusId": switch (availability)
               case "true" return "available"
               case "false" return "lend"
               default return "virtual"},
       $status.callnumber[.]!{"id": .}
     |}
  </s>
  </else>
</action>

<action id="search-details">
  <page url="{$baseurl}/Record/{$book._recordId}" templateFile="searchDetails" />
</action>




<action id="order-single">
  <call action="internal-login"/>
  <if test="matches($holding._orderUrl, 'Holdings.*login')">
    <page url="{$holding._orderUrl}"> </page>
    <pattern><t:s>$holding._orderUrl := .//a/@href[contains(., "Hold?")]</t:s></pattern>
  </if>
  <page url="{$holding._orderUrl}" templateFile="orderConfirmation"> </page>
</action>

<action id="internal-order-location">
  <if test="not( $choose-result instance of xs:decimal and $choose-result eq 0 )">
    <s>$form := request-combine($form, {"gatheredDetails[pickUpLocation]": $choose-result}),
       $confirm-result := true()
    </s>
    <call action="internal-order-confirmed"/>
  </if>
</action>

<action id="internal-order-confirmed">
  <if test="$confirm-result">
    <page url="{$form}"/>
    <pattern>
      <t:switch prioritized="true">
        <div class="alert-success">{$book.status := "ordered"}</div>
        <div class="alert-danger">{vl:raise(.)}</div>
        <div class="alert-info">{$book.status := "ordered"}</div>
      </t:switch>  
    </pattern>
  </if>
</action>

<action id="catalogue">
  <variable name="url" value="{$baseurl}"/>
</action>



</actions>
