#!/usr/bin/env node

const { JSDOM, VirtualConsole } = require("jsdom");
const fs = require("fs");

const angularPath = "/usr/share/javascript/angular.js/angular.min.js";
const angularResource = "/usr/share/javascript/angular.js/angular-resource.min.js";
const angularMocks = "/usr/share/javascript/angular.js/angular-mocks.js";

const angularJS          = fs.readFileSync(angularPath, "utf-8");
const angularResourceJS  = fs.readFileSync(angularResource, "utf-8");
const angularMocksJS     = fs.readFileSync(angularMocks, "utf-8");

const html = `
<!DOCTYPE html>
<html>
<head>
  <script>${angularJS}</script>
  <script>${angularResourceJS}</script>
  <script>${angularMocksJS}</script>

  <script>
    class AppCtrl {
      constructor($resource) {
        this.$resource = $resource;
        this.urlSuffix = null;
        this.duration = '(N/A)';
        this.setUrlSuffixWithSlashesPowerOf2Exponent(17); // 131,078 slashes
        this.runTest();
      }

      setUrlSuffixWithSlashesPowerOf2Exponent(exp) {
        this.urlSuffix = 'foo' + '/'.repeat(2 ** exp) + 'bar';
      }

      runTest() {
        const api = this.$resource(
          '/api/test/' + this.urlSuffix,
          {},
          { query: { method: 'GET', isArray: false } }
        );

        const start = Date.now();
        const res = api.query();
        const end = Date.now();

        this.duration = ((end - start) / 1000).toFixed(2);
        console.log(\`Query setup time: \${this.duration} sec\`);
	if (this.duration > 20) {
	  console.log("[E] It took too long!");
	  window.process.exit(2);
	} else {
	  window.process.exit(0);
	}

        // Clean up
        res.$cancelRequest();
      }
    }

    angular.module('app', ['ngResource', 'ngMockE2E'])
      .controller('AppCtrl', ['$resource', AppCtrl])
      .run(['$httpBackend', function($httpBackend) {
        $httpBackend.whenGET(/^\\/api\\/test\\/.*$/)
                    .respond(200, { ok: true });
      }]);
  </script>
</head>
<body ng-app="app" ng-controller="AppCtrl as ctrl">
</body>
</html>
`;

const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(console);

const dom = new JSDOM(html, {
  runScripts: "dangerously",
  resources: "usable",
  virtualConsole
});
dom.window.process = process;

dom.window.document.addEventListener("DOMContentLoaded", () => {
  const angular = dom.window.angular;
  angular.element(dom.window.document).ready(() => {
    angular.bootstrap(dom.window.document, ['app']);
  });
});

