"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _axios = _interopRequireDefault(require("axios"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var MrCodeGame = function MrCodeGame(_ref, ref) {
  var _ref$key = _ref.key,
      key = _ref$key === void 0 ? '' : _ref$key;

  var _useState = (0, _react.useState)(key),
      _useState2 = _slicedToArray(_useState, 2),
      botId = _useState2[0],
      setbotId = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isOnline = _useState4[0],
      setisOnline = _useState4[1];

  var _useState5 = (0, _react.useState)('Offline'),
      _useState6 = _slicedToArray(_useState5, 2),
      status = _useState6[0],
      setstatus = _useState6[1];

  var input = (0, _react.useRef)();

  var handleInputChange = function handleInputChange(e) {
    setbotId(e.target.value);
  };

  var handleConnect =
  /*#__PURE__*/
  function () {
    var _ref2 = _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee() {
      var response;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              setstatus('Connecting');
              _context.next = 4;
              return _axios["default"].post('https://us-central1-coding-arena-2004b.cloudfunctions.net/isMRCodeConnected', {
                apikey: botId
              });

            case 4:
              response = _context.sent;
              console.log(response);
              setstatus('Online');
              _context.next = 12;
              break;

            case 9:
              _context.prev = 9;
              _context.t0 = _context["catch"](0);
              setstatus('Offline');

            case 12:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 9]]);
    }));

    return function handleConnect() {
      return _ref2.apply(this, arguments);
    };
  }();

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      sendToBot: sendToBot
    };
  });

  var sendToBot =
  /*#__PURE__*/
  function () {
    var _ref3 = _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee2(code) {
      var codeToSend, response;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              setstatus('Executing...');
              codeToSend = "\nfrom m5stack import *\nfrom m5ui import *\nfrom uiflow import *\nimport hat\n\nsetScreenColor(0x111111)\n\nhat_BeetleC0 = hat.get(hat.BEETLEC)\ndef moveForward(duration, speed = 80):\n  hat_BeetleC0.SetPulse(0, speed)\n  hat_BeetleC0.SetPulse(1, speed)\n  wait_ms(duration)\n  hat_BeetleC0.SetPulse(0, 0)\n  hat_BeetleC0.SetPulse(1, 0)\ndef moveBackward(duration, speed = 80):\n  hat_BeetleC0.SetPulse(0, -speed)\n  hat_BeetleC0.SetPulse(1, -speed)\n  wait_ms(duration)\n  hat_BeetleC0.SetPulse(0, 0)\n  hat_BeetleC0.SetPulse(1, 0)\ndef turnLeft(duration, speed = 80):\n  hat_BeetleC0.SetPulse(0,0)\n  hat_BeetleC0.SetPulse(1, speed)\n  wait_ms(duration)\n  hat_BeetleC0.SetPulse(0, 0)\n  hat_BeetleC0.SetPulse(1, 0)\ndef turnRight(duration, speed = 80):\n  hat_BeetleC0.SetPulse(0, speed)\n  hat_BeetleC0.SetPulse(1, 0)\n  wait_ms(duration)\n  hat_BeetleC0.SetPulse(0, 0)\n  hat_BeetleC0.SetPulse(1, 0)\n".concat(code, "\n    ");
              _context2.prev = 2;
              _context2.next = 5;
              return _axios["default"].post("https://us-central1-coding-arena-2004b.cloudfunctions.net/execMRCode", {
                apikey: botId,
                code: codeToSend
              });

            case 5:
              response = _context2.sent;
              _context2.next = 13;
              break;

            case 8:
              _context2.prev = 8;
              _context2.t0 = _context2["catch"](2);
              setstatus('Fail to execute');
              setTimeout(function () {
                return handleConnect();
              }, 3000);
              return _context2.abrupt("return");

            case 13:
              setstatus('Executed');
              setTimeout(function () {
                return handleConnect();
              }, 3000);
              return _context2.abrupt("return", {
                codeToSend: codeToSend,
                response: response
              });

            case 16:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[2, 8]]);
    }));

    return function sendToBot(_x) {
      return _ref3.apply(this, arguments);
    };
  }();

  var statusColor = {
    Online: 'green',
    Offline: 'red',
    Executed: 'green',
    'Fail to execute': 'red',
    Connecting: 'yellow'
  };
  return _react["default"].createElement("div", {
    style: {
      textAlign: 'center'
    }
  }, _react["default"].createElement("input", {
    style: {
      width: '100%',
      padding: 16,
      fontSize: '4rem',
      textAlign: 'center'
    },
    ref: input,
    value: botId,
    placeholder: "bot ID",
    onChange: handleInputChange
  }), _react["default"].createElement("button", {
    onClick: handleConnect,
    style: {
      width: '100%',
      fontSize: '3rem'
    }
  }, "Connect"), _react["default"].createElement("div", {
    style: {
      padding: 16,
      fontSize: '3rem'
    }
  }, _react["default"].createElement("div", null, "Status"), _react["default"].createElement("div", {
    style: {
      color: statusColor[status] || 'black'
    }
  }, status)));
};

var _default = (0, _react.forwardRef)(MrCodeGame);

exports["default"] = _default;