import React from "react";
import { render } from "react-dom";

import { Provider } from "react-redux";

import App from "./App";
import { store } from "./store/store";
import { KeyCodeRaw } from "./utils/KeyCode";
import QRCodeMin from "!!raw-loader!./utils/qrcode.min.js";
import CryptoJsMin from "!!raw-loader!./utils/crypto-js.min_4.0.0.js";

let appElement = (
  <Provider store={store}>
    <App />
  </Provider>
);

if (typeof window === "object") {
  if (!window.Element.prototype.closest) {
    window.Element.prototype.closest = function (selector) {
      var element = this;
      while (element) {
        if (element.matches(selector)) {
          return element;
        }
        element = element.parentElement;
      }
      return null;
    };
  }

  // debug for Chromium v38
  if (window.navigator.userAgent.includes("Chrome/38.0.2125.0")) {
    const getFalseOnRepeat = (event) => {
      if (event.repeat && event.keyCode === 13) {
        console.log("KeyUp Event / This browser is old: Chrome/38.0.2125.0");
        Object.defineProperty(event, "repeat", {
          get: function () {
            return false;
          },
        });
      }
    };

    document.addEventListener("keyup", getFalseOnRepeat, true);
  }

  // Adding the 'key' option to KeyboardEvent in webOS3.0
  if (!("key" in window.KeyboardEvent.prototype)) {
    console.log(
      "KeyDown Event / This browser does not have a 'key' value for KeyboardEvent"
    );
    Object.defineProperty(window.KeyboardEvent.prototype, "key", {
      get: function () {
        if (KeyCodeRaw[this.keyCode]) {
          return KeyCodeRaw[this.keyCode];
        }
        return this.keyCode;
      },
    });
  }

  let qrScript = document.createElement("script");
  qrScript.innerText = QRCodeMin;
  document.body.appendChild(qrScript);

  let cryptoScript = document.createElement("script");
  cryptoScript.innerText = CryptoJsMin;
  document.body.appendChild(cryptoScript);



  window.store = store;

  render(
		appElement,
		document.getElementById('root')
	);
  appElement = null;
}

export default appElement;
