const EVENT_TYPE = "dashboard.window.eval";

// const sandboxScript = `
// var handler = {
//   get: (target, prop, receiver) => (target.sandboxContext[prop] || Reflect.get(target, prop, receiver))
// };
// var sandboxProxy = { _window: window, window: new Proxy(window, handler) };
// with(sandboxProxy) {
//   try {
//     window.postMessage.call(_window, { data: eval("window.location.href"), type: "dashboard.window.eval", });
//   } catch (e) {
//     window.postMessage.call(_window, { err: e, type: "dashboard.window.eval" });
//   }
// }
// `;

export default {
  type: EVENT_TYPE,
  getJs: () => `
    case '${EVENT_TYPE}':
      var handleEvalResult = function(event) {
        if (event.data && event.data.type && event.data.type === "dashboard.window.eval") {
          if (event.data.err) {
            window.spSocket.send({ eventName: "dashboard", data: { type: "dashboard.window.evalResponse", err: event.data.err } });
            return;
          }
          window.spSocket.send({ eventName: "dashboard", data: { type: "dashboard.window.evalResponse", data: event.data.data } });
        }
      }
  
      var propertiesToCover = ["location"];
      var createSandboxContext = function(srcObj, propertiesToCover) {
        var context = {};
        Object.keys(srcObj).forEach(function (key) {
          if (srcObj.hasOwnProperty(key) && propertiesToCover.indexOf(key) > -1) {
            context[key] = srcObj[key];
          }
        });
        return context;
      }

      var createIframe = function() {
        var $iframe = document.getElementById("dashboard-sandbox");
        if (!$iframe) {
          $iframe = document.createElement("iframe");
          $iframe.setAttribute("id", "dashboard-sandbox");
          $iframe.setAttribute("sandbox", "allow-same-origin allow-scripts");
          $iframe.style.display = "none";
        }
        $iframe.innerHTML = "";

        return $iframe;
      };

      var initializeSandbox = function(code) {
        // var $iframe = createIframe();
        var $script = document.getElementById('sandbox');

        if (!$script) {
          $script = document.createElement("script");
          $script.setAttribute('id', 'sandbox');
        }

        $script.innerText = '(function() { return eval(' + code + ') })()';

        document.body.appendChild($script);

        // $iframe.contentWindow.addEventListener("message", handleEvalResult, false);
        // $iframe.contentWindow.sandboxContext = createSandboxContext(window, propertiesToCover);
        // $iframe.contentDocument.body.appendChild($script);
      }

      initializeSandbox(data.code);
      break;\n
  `,
};
