<!--
The request to this GraphQL server provided the header "Accept: text/html"
and as a result has been presented GraphiQL - an in-browser IDE for
exploring GraphQL.
If you wish to receive JSON, provide the header "Accept: application/json" or
add "&raw" to the end of the URL within a browser.
-->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>{{graphiql_html_title}}</title>
  <meta name="robots" content="noindex" />
  <meta name="referrer" content="origin" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
    #graphiql {
      height: 100vh;
    }
  </style>
  <link href="//cdn.jsdelivr.net/npm/graphiql@{{graphiql_version}}/graphiql.css" rel="stylesheet" />
  <script src="//cdn.jsdelivr.net/npm/promise-polyfill@8.1.3/dist/polyfill.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/unfetch@4.1.0/dist/unfetch.umd.js"></script>
  <script src="//cdn.jsdelivr.net/npm/react@16.13.1/umd/react.production.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/react-dom@16.13.1/umd/react-dom.production.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/graphiql@{{graphiql_version}}/graphiql.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/subscriptions-transport-ws@0.9.16/browser/client.js"></script>
  <script src="//cdn.jsdelivr.net/npm/graphiql-subscriptions-fetcher@0.0.2/browser/client.js"></script>
</head>
<body>
  <div id="graphiql">Loading...</div>
  <script>
    var default_query = `query test_query($url: String!, $name: GenericScalar!) {
  result: fetch(url: $url) {
    name: constant(value: $name)
    website: link(xpath: "//a[contains(@class, 'site-link')]")
    summary: group {
      total_emp_expenses: text(xpath: "//*[@id='emp-exp-total']", data_type: INT)
      total_shown_expenses: text(xpath: "//*[@id='exp-total']/span[2]", data_type: INT)
      total_approved_expenses: text(xpath: "//*[@id='emp-exp-approved']/span[2]", data_type: INT)
    }
    summary1: group {
      total_shown_expenses: regex(xpath: "//*[@id='exp-total']", pattern: "(\\\\d+)")
    }
    exp_details: list(xpath: "//div[@class='card']") {
      name: text(xpath: "//div[contains(@class,'expense-emp-name')]")
      user_id: query_params(xpath: "//a/@href", name: "user")
      amount: group {
        money: text(xpath: "//h6[contains(@class,'expense-amount')]/span[1]", data_type: INT)
        name: text(xpath: "//h6[contains(@class,'expense-amount')]/span[2]")
      }
      approval_id: attr(xpath: "//button[contains(@class, 'expense-approve')]", name: "id")
    }
    exp_details_method2: list(xpath: "//div[@class='card']") {
      name: text(xpath: "//div[@class='card-title title expense-emp-name']")
    }
    exp_details_method3: list(xpath: "//div[@class='card']") {
      name1: text(xpath: ".//div[@class='card-title title expense-emp-name']")
      name2: text(xpath: ".//div[contains(@class,'expense-emp-name')]")
    }
  }
}
`;
    var variables = `{
	"url": "http://localhost:5000/scrapqd/sample_page/",
	"name": "local-testing"
}`;

    // Collect the URL parameters
    var parameters = {};
    window.location.search.substr(1).split('&').forEach(function (entry) {
      var eq = entry.indexOf('=');
      if (eq >= 0) {
        parameters[decodeURIComponent(entry.slice(0, eq))] =
          decodeURIComponent(entry.slice(eq + 1));
      }
    });
    // Produce a Location query string from a parameter object.
    function locationQuery(params) {
      return '?' + Object.keys(params).filter(function (key) {
        return Boolean(params[key]);
      }).map(function (key) {
        return encodeURIComponent(key) + '=' +
          encodeURIComponent(params[key]);
      }).join('&');
    }
    // Derive a fetch URL from the current URL, sans the GraphQL parameters.
    var graphqlParamNames = {
      query: true,
      variables: true,
      operationName: true
    };
    var otherParams = {};
    for (var k in parameters) {
      if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {
        otherParams[k] = parameters[k];
      }
    }
    // Configure the subscription client
    let subscriptionsFetcher = null;
    if ('{{subscription_url}}') {
      let subscriptionsClient = new SubscriptionsTransportWs.SubscriptionClient(
        '{{ subscription_url }}',
        { reconnect: true }
      );
      subscriptionsFetcher = GraphiQLSubscriptionsFetcher.graphQLFetcher(
        subscriptionsClient,
        graphQLFetcher
      );
    }
    var fetchURL = locationQuery(otherParams);
    var init = true;
    // Defines a GraphQL fetcher using the fetch API.
    function graphQLFetcher(graphQLParams, opts) {
      if(!init) displayResultTab(true);
      return fetch(fetchURL, {
        method: 'post',
        headers: Object.assign(
          {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          opts && opts.headers,
        ),
        body: JSON.stringify(graphQLParams),
        credentials: 'include',
      }).then(function (response) {
        init = false;
        return response.json();
      });
    }
    // When the query and variables string is edited, update the URL bar so
    // that it can be easily shared.
    function onEditQuery(newQuery) {
      parameters.query = newQuery;
    }
    function onEditVariables(newVariables) {
      parameters.variables = newVariables;
    }
    function onEditHeaders(newHeaders) {
      parameters.headers = newHeaders;
    }
    function onEditOperationName(newOperationName) {
      parameters.operationName = newOperationName;
    }
    // Render <GraphiQL /> into the body.
    ReactDOM.render(
      React.createElement(GraphiQL, {
        fetcher: subscriptionsFetcher || graphQLFetcher,
        onEditQuery: onEditQuery,
        onEditVariables: onEditVariables,
        onEditOperationName: onEditOperationName,
        query: default_query,
        response: {{result|tojson}},
        variables: variables,
        headers: {{headers|tojson}},
        operationName: {{operation_name|tojson}},
        defaultQuery: {{default_query|tojson}}
      }),
      document.getElementById('graphiql')
    );
    function addResultDisplayBtn(){
        var button = document.createElement("a");
        button.innerHTML = "Hide";
        button.value = "hide";
        button.id = "resultDisplayBtn";
        button.style.position = 'absolute';
        button.style.top= '12px';
        button.style.right= '110px';
        button.style.textAlign= 'center';
        button.classList.add('toolbar-button');
        document.getElementsByClassName("toolbar")[0].appendChild(button);
        displayResultTab(false);
        button.addEventListener ("click", function() {
            var value = button.innerHTML.toLowerCase();
            var show = value == 'show' ? true: false;
            displayResultTab(show)
        });
    }

    function displayResultTab(show=true){
        var button = document.getElementById("resultDisplayBtn");
        var display = show ? 'block': 'none';
        var value = show ? 'Hide': 'Show';
        button.innerHTML = value;
        document.querySelector('.resultWrap').style.display = display ;
    }
    addResultDisplayBtn();
    document.querySelector(".graphiql-container .title").innerHTML = "{{graphiql_html_title}}";
    document.querySelector("button[title^='Merge Query']").style.display = "none";
    init = false;
  </script>
</body>
</html>