"use strict";

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

var _phaser = _interopRequireDefault(require("phaser"));

var _lodash = _interopRequireDefault(require("lodash"));

var _firebaseApp = _interopRequireDefault(require("../../../helper/firebaseApp"));

var _jsInterpreter = _interopRequireDefault(require("js-interpreter"));

var _firestore = require("rxfire/firestore");

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Player =
/*#__PURE__*/
function (_Phaser$GameObjects$S) {
  _inherits(Player, _Phaser$GameObjects$S);

  // 0 = down, 1 = right, 2 = up, 3 = left
  function Player(_ref) {
    var _this;

    var scene = _ref.scene,
        x = _ref.x,
        y = _ref.y,
        key = _ref.key,
        frame = _ref.frame,
        _ref$direction = _ref.direction,
        direction = _ref$direction === void 0 ? 'right' : _ref$direction,
        _ref$playerId = _ref.playerId,
        _playerId = _ref$playerId === void 0 ? '' : _ref$playerId,
        _ref$playerName = _ref.playerName,
        playerName = _ref$playerName === void 0 ? '' : _ref$playerName;

    _classCallCheck(this, Player);

    console.log('player init');
    _this = _possibleConstructorReturn(this, _getPrototypeOf(Player).call(this, scene, 0, 0, key, frame)); // this.scene.physics.world.enable(this)

    _defineProperty(_assertThisInitialized(_this), "animKeys", ['down', 'right', 'up', 'left']);

    _defineProperty(_assertThisInitialized(_this), "direction", 3);

    _defineProperty(_assertThisInitialized(_this), "moving", false);

    _defineProperty(_assertThisInitialized(_this), "movingTo", null);

    _defineProperty(_assertThisInitialized(_this), "subscribeFirestore", function () {
      var roomId = _this.scene.roomId;
      var playerId = _this.playerId;
      (0, _firestore.doc)(_firebaseApp["default"].firestore().collection('room').doc(roomId).collection('players').doc(playerId)).subscribe(function (snap) {
        var data = snap.data();

        if (!data) {
          return;
        } // load location from firestore


        if (data.x && _this.prevData.x !== data.x) {
          console.log('set x');
          _this.initialLocation.x = data.x;
          _this.container.x = data.x;
        }

        if (data.y && _this.prevData.y !== data.y) {
          console.log('set y');
          _this.initialLocation.y = data.y;
          _this.container.y = data.y;
        } // run code


        if (_this.scene && playerId !== _this.scene.game.playerId) {
          if (_this.prevData.running !== data.running && data.running && !_this.moving) {
            _this.container.x = _this.initialLocation.x;
            _this.container.y = _this.initialLocation.y;

            _this.runCode(data.code);
          }
        }

        _this.prevData = data;
      });
    });

    _defineProperty(_assertThisInitialized(_this), "getSurroundingTiles", function (currentLayerIndex, top, bottom, left, right) {
      if (_lodash["default"].isNil(currentLayerIndex)) {
        currentLayerIndex = _this.scene.map.currentLayerIndex;
      }

      var bounds = _this.getBounds(); // find middle


      var currentTileXY = _this.scene.map.worldToTileXY(bounds.centerX, bounds.centerY, 16);

      if (!_lodash["default"].isNil(top) && !_lodash["default"].isNil(bottom) && !_lodash["default"].isNil(left) && !_lodash["default"].isNil(right) || currentLayerIndex === -1) {
        return {
          top: top,
          bottom: bottom,
          left: left,
          right: right
        };
      }

      if (_lodash["default"].isNil(top)) {
        top = _this.scene.map.getTileAt(currentTileXY.x, currentTileXY.y - 1, false, currentLayerIndex);
      }

      if (_lodash["default"].isNil(bottom)) {
        bottom = _this.scene.map.getTileAt(currentTileXY.x, currentTileXY.y + 1, false, currentLayerIndex);
      }

      if (_lodash["default"].isNil(left)) {
        left = _this.scene.map.getTileAt(currentTileXY.x - 1, currentTileXY.y, false, currentLayerIndex);
      }

      if (_lodash["default"].isNil(right)) {
        right = _this.scene.map.getTileAt(currentTileXY.x + 1, currentTileXY.y, false, currentLayerIndex);
      }

      return _this.getSurroundingTiles(currentLayerIndex - 1, top, bottom, left, right);
    });

    _defineProperty(_assertThisInitialized(_this), "checkCanMove", function () {
      var surroundingTiles = _this.getSurroundingTiles();

      return {
        top: !_lodash["default"].get(surroundingTiles, 'top.collides', true),
        bottom: !_lodash["default"].get(surroundingTiles, 'bottom.collides', true),
        left: !_lodash["default"].get(surroundingTiles, 'left.collides', true),
        right: !_lodash["default"].get(surroundingTiles, 'right.collides', true)
      };
    });

    _defineProperty(_assertThisInitialized(_this), "runCode",
    /*#__PURE__*/
    function () {
      var _ref2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee5(code) {
        var roomId, playerId, player, interpreter, run;
        return regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                roomId = _this.scene.roomId;
                playerId = _this.playerId;

                if (!(playerId === _this.scene.game.playerId)) {
                  _context5.next = 5;
                  break;
                }

                _context5.next = 5;
                return _firebaseApp["default"].firestore().collection('room').doc(roomId).collection('players').doc(playerId).set({
                  code: code,
                  running: true
                }, {
                  merge: true
                });

              case 5:
                player = _assertThisInitialized(_this);
                interpreter = new _jsInterpreter["default"](code, function (interpreter, scope) {
                  interpreter.setProperty(scope, 'moveForward', interpreter.createAsyncFunction(
                  /*#__PURE__*/
                  function () {
                    var _ref3 = _asyncToGenerator(
                    /*#__PURE__*/
                    regeneratorRuntime.mark(function _callee(callback) {
                      return regeneratorRuntime.wrap(function _callee$(_context) {
                        while (1) {
                          switch (_context.prev = _context.next) {
                            case 0:
                              _context.next = 2;
                              return player.moveForward();

                            case 2:
                              callback();

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

                    return function (_x2) {
                      return _ref3.apply(this, arguments);
                    };
                  }()));
                  interpreter.setProperty(scope, 'turnLeft', interpreter.createAsyncFunction(
                  /*#__PURE__*/
                  function () {
                    var _ref4 = _asyncToGenerator(
                    /*#__PURE__*/
                    regeneratorRuntime.mark(function _callee2(callback) {
                      return regeneratorRuntime.wrap(function _callee2$(_context2) {
                        while (1) {
                          switch (_context2.prev = _context2.next) {
                            case 0:
                              _context2.next = 2;
                              return player.turnLeft();

                            case 2:
                              callback();

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

                    return function (_x3) {
                      return _ref4.apply(this, arguments);
                    };
                  }()));
                  interpreter.setProperty(scope, 'turnRight', 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 player.turnRight();

                            case 2:
                              callback();

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

                    return function (_x4) {
                      return _ref5.apply(this, arguments);
                    };
                  }()));
                });

                run =
                /*#__PURE__*/
                function () {
                  var _ref6 = _asyncToGenerator(
                  /*#__PURE__*/
                  regeneratorRuntime.mark(function _callee4() {
                    return regeneratorRuntime.wrap(function _callee4$(_context4) {
                      while (1) {
                        switch (_context4.prev = _context4.next) {
                          case 0:
                            if (!interpreter.run()) {
                              _context4.next = 4;
                              break;
                            }

                            setTimeout(run, 500);
                            _context4.next = 7;
                            break;

                          case 4:
                            if (playerId === _this.scene.game.playerId) {
                              _this.scene.complete();
                            }

                            _context4.next = 7;
                            return _firebaseApp["default"].firestore().collection('room').doc(roomId).collection('players').doc(playerId).set({
                              running: false
                            }, {
                              merge: true
                            });

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

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

                run();

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

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

    _this.initialLocation = {
      x: x,
      y: y
    };
    _this.prevData = {
      // use to detect doc changes
      x: 0,
      y: 0,
      running: false
    };
    _this.playerName = playerName || _playerId;
    _this.playerId = _playerId;

    _this.scene.add.existing(_assertThisInitialized(_this));

    _this.container = _this.scene.add.container(x, y); // this.containerBody = this.scene.add.container(128, 128).setSize(256, 256)

    _this.scene.physics.add.collider(_assertThisInitialized(_this), _this.scene.groundLayer);

    _this.scene.physics.add.collider(_assertThisInitialized(_this), _this.scene.wallLayer);

    _this.scene.physics.world.enable(_assertThisInitialized(_this));

    _this.scene.physics.world.enable(_this.container); // this.scene.physics.world.enable(this.containerBody)


    _this.text = _this.scene.add.text(128, 300, _this.playerName, {
      fontSize: 64
    }).setOrigin(0.5, 0.5); // this.container.add(this.containerBody)

    _this.container.add(_assertThisInitialized(_this));

    _this.container.add(_this.text);

    _this.originX = 0;
    _this.originY = 0;
    _this.direction = _this.animKeys.indexOf(direction);

    if (_this.direction === -1) {
      _this.direction = 1;
    }

    _this.subscribeFirestore();

    return _this;
  }

  _createClass(Player, [{
    key: "turnLeft",
    value: function turnLeft() {
      if (this.moving) {
        throw new Error('Move not finish');
      }

      this.direction = (this.direction + 1) % 4;
      return new Promise(function (resolve) {
        setTimeout(resolve, 100);
      });
    }
  }, {
    key: "turnRight",
    value: function turnRight() {
      if (this.moving) {
        throw new Error('Move not finish');
      }

      this.direction = Math.abs(this.direction + 3) % 4;
      return new Promise(function (resolve) {
        setTimeout(resolve, 100);
      });
    }
  }, {
    key: "moveForward",
    value: function moveForward() {
      var _this2 = this;

      if (this.moving) {
        throw new Error('Move not finish');
      }

      switch (this.direction) {
        case 0:
          this.moveTo(this.container.x, this.container.y + 256);
          break;

        case 1:
          this.moveTo(this.container.x + 256, this.container.y);
          break;

        case 2:
          this.moveTo(this.container.x, this.container.y - 256);
          break;

        case 3:
          this.moveTo(this.container.x - 256, this.container.y);
          break;
      }

      return new Promise(function (resolve) {
        _this2.scene.game.events.on('moveEnd', function () {
          setTimeout(resolve, 100);
        });
      });
    }
  }, {
    key: "moveTo",
    value: function moveTo(x, y) {
      var playerId = this.playerId;

      if (!this.canMoveForward()) {
        if (playerId === this.scene.game.playerId) {
          this.scene.complete();
        }

        return;
      }

      this.movingTo = {
        x: x,
        y: y
      };
      this.moving = true; // this.scene.physics.moveToObject(this, new Phaser.Math.Vector2(x, y), 600)

      this.scene.physics.moveTo(this.container, x, y, 600);
    }
  }, {
    key: "checkMoveEnd",
    value: function checkMoveEnd() {
      if (!this.movingTo) {
        return;
      }

      var xEnd = Math.abs(this.container.x - this.movingTo.x) < 25;
      var yEnd = Math.abs(this.container.y - this.movingTo.y) < 25;

      if (xEnd && yEnd) {
        this.moving = false;
        this.container.body.reset(this.movingTo.x, this.movingTo.y);
        console.log('stop moving', this.movingTo.x, this.movingTo.y); // this.x = this.movingTo.x
        // this.y = this.movingTo.y

        this.movingTo = null;
        this.scene.game.events.emit('moveEnd');
      }
    }
  }, {
    key: "canMove",
    value: function canMove(direction) {
      // let _x = this.x
      // let _y = this.y
      var touching = this.checkCanMove();
      var checkTile = [touching.bottom, touching.right, touching.top, touching.left];
      var checkDirection = direction % 4;
      return checkTile[checkDirection];
    }
  }, {
    key: "canMoveLeft",
    value: function canMoveLeft() {
      return this.canMove(this.direction + 1);
    }
  }, {
    key: "canMoveRight",
    value: function canMoveRight() {
      return this.canMove(this.direction + 3);
    }
  }, {
    key: "canMoveForward",
    value: function canMoveForward() {
      return this.canMove(this.direction);
    }
  }, {
    key: "update",
    value: function update(time, delta, cursors) {
      if (this.moving) {
        this.checkMoveEnd();
      }

      if (this.anims) {
        this.anims.play("".concat(this.moving ? 'walking-' : '').concat(this.animKeys[this.direction]), true);
      }
    }
  }]);

  return Player;
}(_phaser["default"].GameObjects.Sprite);

var _default = Player;
exports["default"] = _default;