"use strict";

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

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

var _UnityGameWrapper = _interopRequireDefault(require("../UnityGameWrapper/UnityGameWrapper"));

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 WonderfarmGame = (0, _react.forwardRef)(function (_ref, ref) {
  var editor = _ref.editor,
      _ref$onLevelComplete = _ref.onLevelComplete,
      onLevelComplete = _ref$onLevelComplete === void 0 ? function () {} : _ref$onLevelComplete;

  var _useState = (0, _react.useState)(),
      _useState2 = _slicedToArray(_useState, 2),
      unityContent = _useState2[0],
      setunityContent = _useState2[1];

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

  var _useState5 = (0, _react.useState)(0),
      _useState6 = _slicedToArray(_useState5, 2),
      _score = _useState6[0],
      setScore = _useState6[1];

  var _useState7 = (0, _react.useState)(0),
      _useState8 = _slicedToArray(_useState7, 2),
      _lvl = _useState8[0],
      setLvl = _useState8[1];

  var _useState9 = (0, _react.useState)(0),
      _useState10 = _slicedToArray(_useState9, 2),
      _time = _useState10[0],
      setTime = _useState10[1];

  (0, _react.useEffect)(function () {}, [lvcomplete, _lvl, _time, _score]);
  (0, _react.useEffect)(function () {
    if (_lvl > 0 && _time > 0 && _score > 0) {
      console.log('item', _score, _lvl, _time);
      onLevelComplete(_score, _lvl, _time);
    }
  }, [_lvl, _time, _score]);

  var init = function init(content) {
    content.on("MoveEnd", function () {
      console.log('move end'); // debugger
      // movingResolver()
    });
    content.on('ResetEditor', function () {
      console.log('editor', editor);
      editor.current && editor.current.clear();
    });
    content.on('LevelComplete', function (score) {
      console.log('level complete', score);
      editor.current && editor.current.clear(); // onLevelComplete(score);
    });
    content.on('LevelStart', function (mission) {
      console.log('level start', mission); // editor.current && editor.current.clear()
    });
    content.on('GameScore', function (num) {
      // console.log('GameScore', num)
      setScore(num);
      setlvcomplete(true);
    });
    content.on('PlayTime', function (time) {
      // console.log('game time ', time)
      setTime(time);
    });
    content.on('Stage', function (stage) {
      // console.log('game stage ', stage)
      setLvl(stage);
    }); // unityContent.on('GameScore', (score) => { console.log('score', score) })

    setunityContent(content);
  }; // useImparativeHandle(Score, () => ({
  //   // myscore: score
  // })


  (0, _react.useImperativeHandle)(ref, function () {
    return {
      complete: function complete() {// game && game.scene.getScene('GameScene').complete()
      },
      lvComplete: lvcomplete,
      setLvStart: function setLvStart(params) {
        setlvcomplete(false);
      },
      setScore: function setScore(score) {// game && game.scene.getScene('GameScene').setScore(score)
      },
      addScore: function addScore(score) {// game && game.scene.getScene('GameScene').addScore(score)
      },
      player: {
        moveLeft: moveLeft,
        moveRight: moveRight,
        moveUp: moveUp,
        moveDown: moveDown
      },
      run: runCode
    };
  });

  var waitMoveEnd =
  /*#__PURE__*/
  function () {
    var _ref2 = _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee() {
      var _moving;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _moving = new Promise(function (resolve) {
                unityContent.on('MoveEnd', function () {
                  resolve();
                });
              });
              console.log('move end promise'); // unityContent.on('GameScore', (score) => { console.log('score', score) })

              return _context.abrupt("return", _moving);

            case 3:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

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

  var move = function move(command) {
    return (
      /*#__PURE__*/
      _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee2() {
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                unityContent.send("Player", command);
                return _context2.abrupt("return", waitMoveEnd());

              case 2:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }))
    );
  };

  var moveUp = move('moveUp');
  var moveLeft = move('moveLeft');
  var moveRight = move('moveRight');
  var moveDown = move('moveDown');
  var pickItem = move('pickItem');

  var restartLevel = function restartLevel() {
    unityContent.send("ModalCanvas", "ShowLevelFail");
  };

  var score = function score(num) {
    return !!StateScore ? StateScore : !!num;
  };

  var runCode =
  /*#__PURE__*/
  function () {
    var _ref4 = _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee9(code) {
      var interpreter, run, _run;

      return regeneratorRuntime.wrap(function _callee9$(_context9) {
        while (1) {
          switch (_context9.prev = _context9.next) {
            case 0:
              _run = function _ref11() {
                _run = _asyncToGenerator(
                /*#__PURE__*/
                regeneratorRuntime.mark(function _callee8() {
                  return regeneratorRuntime.wrap(function _callee8$(_context8) {
                    while (1) {
                      switch (_context8.prev = _context8.next) {
                        case 0:
                          if (interpreter.run()) {
                            setTimeout(run, 50);
                          } else {
                            // player.scene.complete()
                            restartLevel();
                          }

                        case 1:
                        case "end":
                          return _context8.stop();
                      }
                    }
                  }, _callee8);
                }));
                return _run.apply(this, arguments);
              };

              run = function _ref10() {
                return _run.apply(this, arguments);
              };

              interpreter = new Interpreter(code, function (interpreter, scope) {
                interpreter.setProperty(scope, 'moveUp', interpreter.createAsyncFunction(
                /*#__PURE__*/
                function () {
                  var _ref5 = _asyncToGenerator(
                  /*#__PURE__*/
                  regeneratorRuntime.mark(function _callee3(callback) {
                    return regeneratorRuntime.wrap(function _callee3$(_context3) {
                      while (1) {
                        switch (_context3.prev = _context3.next) {
                          case 0:
                            _context3.next = 2;
                            return moveUp();

                          case 2:
                            callback();

                          case 3:
                          case "end":
                            return _context3.stop();
                        }
                      }
                    }, _callee3);
                  }));

                  return function (_x2) {
                    return _ref5.apply(this, arguments);
                  };
                }()));
                interpreter.setProperty(scope, 'moveLeft', interpreter.createAsyncFunction(
                /*#__PURE__*/
                function () {
                  var _ref6 = _asyncToGenerator(
                  /*#__PURE__*/
                  regeneratorRuntime.mark(function _callee4(callback) {
                    return regeneratorRuntime.wrap(function _callee4$(_context4) {
                      while (1) {
                        switch (_context4.prev = _context4.next) {
                          case 0:
                            _context4.next = 2;
                            return moveLeft();

                          case 2:
                            callback();

                          case 3:
                          case "end":
                            return _context4.stop();
                        }
                      }
                    }, _callee4);
                  }));

                  return function (_x3) {
                    return _ref6.apply(this, arguments);
                  };
                }()));
                interpreter.setProperty(scope, 'moveRight', interpreter.createAsyncFunction(
                /*#__PURE__*/
                function () {
                  var _ref7 = _asyncToGenerator(
                  /*#__PURE__*/
                  regeneratorRuntime.mark(function _callee5(callback) {
                    return regeneratorRuntime.wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            _context5.next = 2;
                            return moveRight();

                          case 2:
                            callback();

                          case 3:
                          case "end":
                            return _context5.stop();
                        }
                      }
                    }, _callee5);
                  }));

                  return function (_x4) {
                    return _ref7.apply(this, arguments);
                  };
                }()));
                interpreter.setProperty(scope, 'moveDown', interpreter.createAsyncFunction(
                /*#__PURE__*/
                function () {
                  var _ref8 = _asyncToGenerator(
                  /*#__PURE__*/
                  regeneratorRuntime.mark(function _callee6(callback) {
                    return regeneratorRuntime.wrap(function _callee6$(_context6) {
                      while (1) {
                        switch (_context6.prev = _context6.next) {
                          case 0:
                            _context6.next = 2;
                            return moveDown();

                          case 2:
                            callback();

                          case 3:
                          case "end":
                            return _context6.stop();
                        }
                      }
                    }, _callee6);
                  }));

                  return function (_x5) {
                    return _ref8.apply(this, arguments);
                  };
                }()));
                interpreter.setProperty(scope, 'pickItem', interpreter.createAsyncFunction(
                /*#__PURE__*/
                function () {
                  var _ref9 = _asyncToGenerator(
                  /*#__PURE__*/
                  regeneratorRuntime.mark(function _callee7(callback) {
                    return regeneratorRuntime.wrap(function _callee7$(_context7) {
                      while (1) {
                        switch (_context7.prev = _context7.next) {
                          case 0:
                            _context7.next = 2;
                            return pickItem();

                          case 2:
                            callback();

                          case 3:
                          case "end":
                            return _context7.stop();
                        }
                      }
                    }, _callee7);
                  }));

                  return function (_x6) {
                    return _ref9.apply(this, arguments);
                  };
                }()));
              });
              run();

            case 4:
            case "end":
              return _context9.stop();
          }
        }
      }, _callee9);
    }));

    return function runCode(_x) {
      return _ref4.apply(this, arguments);
    };
  }();

  return _react["default"].createElement(_UnityGameWrapper["default"], {
    onCreateUnityContent: init,
    buildURL: "https://reactunity-e510d.firebaseapp.com/Build/wonderfarmbuild.json",
    loaderURL: "https://reactunity-e510d.firebaseapp.com/Build/UnityLoader.js" // buildURL={"https://wonderfarm-codingarena.firebaseapp.com/Build/webgl.json"}
    // loaderURL={"https://wonderfarm-codingarena.firebaseapp.com/Build/UnityLoader.js"}

  });
});
var _default = WonderfarmGame;
exports["default"] = _default;