#!/usr/bin/env node

const { JSDOM } = 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 html = `<!DOCTYPE html>
<html>
<head>
  <script src="${angularPath}"></script>
  <script src="${angularResource}"></script>
  <script src="${angularMocks}"></script>

  <script>
    class AppCtrl {
      static $inject = ['$compile', '$rootScope'];

      ngSrcSet = null;
      ngSrcSetCompiledElem = null;
      timeoutId = null;
      duration = '(N/A)';

      constructor($compile, $rootScope) {
    this.$compile = $compile;
    this.$rootScope = $rootScope;
    this.setNgSrcSetWithSpacesPowerOf2Exponent(20);
      }

      setNgSrcSetWithSpacesPowerOf2Exponent(exponent) {
    this.ngSrcSet = 'http://example.com/image.png 2x,'+(' '.repeat(2 ** exponent))+'http://example.com/image.png';
      }

      compileNgSrcSet() {
        console.log("compileNgSrcSet called")
    clearTimeout(this.timeoutId);

    // Use setTimeout to allow manual $apply calls.
    this.timeoutId = setTimeout(() => {
      try {
        console.dir(this.ngSrcSetCompiledElem)
            this.ngSrcSetCompiledElem[0].innerHtml = (new DOMParser().parseFromString('<img ng-srcset='+this.ngSrcSet+'>','text/html')).body.firstChild;
        console.log(this.ngSrcSetCompiledElem)
        const scope = this.ngSrcSetCompiledElem.scope();

        const start = Date.now();
        //console.log(th)
        this.$compile(this.ngSrcSetCompiledElem)(scope);
        this.$rootScope.$apply();
        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);
            }
      } catch (err) {
        console.error(err);
        console.log("[E] crashed!");
            window.process.exit(3);
      } finally {
        this.$rootScope.$apply(); // apply the duration change
      }
    });
      }
    }
   // Define and configure the app.
   angular.module('app', []).controller('AppCtrl', AppCtrl);
   angular.element(document).ready(() => {
       angular.bootstrap(document, ['app']); 
       console.log("angular ready, sending click");
       setTimeout(() => {
         document.getElementById("compilebtn").click();
       }, 50);
   }); 
  </script>
</head>
<body ng-app="app" ng-controller="AppCtrl as $ctrl">
  <input class="repro-input" type="url" ng-model="$ctrl.ngSrcSet" />
  <p ng-ref="$ctrl.ngSrcSetCompiledElem"></p>
  <button id="compilebtn" ng-click="$ctrl.compileNgSrcSet()">Compile</button>
</body>
</html>
`;
const dom = new JSDOM(html, {
  runScripts: "dangerously",
  resources: "usable",
  pretendToBeVisual: true,
  url: `file://${process.cwd()}/debian/build/`
});
dom.window.process = process;
