"use strict";

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

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

var _Player = _interopRequireDefault(require("../objects/Player"));

var _Objective = _interopRequireDefault(require("../objects/Objective"));

var _KineticScroll = _interopRequireDefault(require("../helper/KineticScroll"));

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

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 GameScene =
/*#__PURE__*/
function (_Phaser$Scene) {
  _inherits(GameScene, _Phaser$Scene);

  function GameScene() {
    var _this;

    _classCallCheck(this, GameScene);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(GameScene).call(this, {
      key: 'GameScene'
    }));

    _defineProperty(_assertThisInitialized(_this), "init",
    /*#__PURE__*/
    function () {
      var _ref2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee(_ref) {
        var _ref$roomId, roomId, _ref$score, score;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _ref$roomId = _ref.roomId, roomId = _ref$roomId === void 0 ? '' : _ref$roomId, _ref$score = _ref.score, score = _ref$score === void 0 ? 0 : _ref$score;
                _this.roomId = roomId;
                _this.score = score;
                _this.oldObjectives = [];

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

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

    _defineProperty(_assertThisInitialized(_this), "joinRoom",
    /*#__PURE__*/
    function () {
      var _ref3 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee2(roomId) {
        var s;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return _firebaseApp["default"].firestore().collection('room').doc(roomId).get();

              case 2:
                s = _context2.sent;

                if (s.exists) {
                  _context2.next = 6;
                  break;
                }

                _this.scene.launch('JoinRoomScene', {
                  error: 'Room not exist'
                });

                return _context2.abrupt("return");

              case 6:
                _this.scene.restart({
                  roomId: roomId,
                  score: 0
                });

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

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

    _defineProperty(_assertThisInitialized(_this), "nextLevel", function () {
      _this.scene.restart({
        roomId: _this.roomId,
        score: 0
      });
    });

    return _this;
  }

  _createClass(GameScene, [{
    key: "preload",
    value: function () {
      var _preload = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee3() {
        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

      function preload() {
        return _preload.apply(this, arguments);
      }

      return preload;
    }()
  }, {
    key: "addScore",
    value: function addScore(score) {
      this.score += score;
      this.setScore(this.score);
    }
  }, {
    key: "setScore",
    value: function setScore(score) {
      this.score = score;
      this.messageScore.setText(this.score);
    }
  }, {
    key: "complete",
    value: function complete() {
      this.scene.launch('StageSummaryScene');
    }
  }, {
    key: "restart",
    value: function restart() {
      this.scene.restart({
        roomId: this.roomId,
        score: 0
      });
    }
  }, {
    key: "create",
    value: function () {
      var _create = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee4() {
        var _this2 = this;

        var roomId, playerId, playerName, roomSnap, roomInfo, mapData, tile1, tile2, groundLayer, wallLayer, decorationsLayer, player, playerTileset, playerTile, pigs, playerQuery;
        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                roomId = this.roomId;
                playerId = this.game.playerId;
                playerName = this.game.playerName || playerId;
                _context4.next = 5;
                return _firebaseApp["default"].firestore().collection('room').doc(roomId).get();

              case 5:
                roomSnap = _context4.sent;
                roomInfo = roomSnap.data();
                this.adminMode = this.game.playerId === roomInfo.adminUserId;

                if (this.adminMode) {
                  this.scene.launch('RoomAdminScene', {
                    roomId: roomId
                  }); // start admin scene
                } else {
                  _firebaseApp["default"].firestore().collection('room').doc(roomId).collection('players').doc(playerId).set({
                    online: true,
                    playerName: playerName
                  }, {
                    merge: true
                  });

                  this.events.on('destroy', function () {
                    _firebaseApp["default"].firestore().collection('room').doc(roomId).collection('players').doc(playerId).set({
                      online: false
                    }, {
                      merge: true
                    });
                  });
                } // this.game.kineticScrolling.start();


                this.kineticScrolling = new _KineticScroll["default"](this); // this.cameras.main.setZoom(0.5)

                mapData = _phaser["default"].Tilemaps.Parsers.Parse('map', _phaser["default"].Tilemaps.Formats.TILED_JSON, require("../assets/map1.json"));
                this.map = new _phaser["default"].Tilemaps.Tilemap(this, mapData);
                tile1 = this.map.addTilesetImage('tile', 'tile');
                tile2 = this.map.addTilesetImage('objects', 'objects');
                groundLayer = this.map.createStaticLayer('ground', [tile1], 0, 0);
                wallLayer = this.map.createStaticLayer('wall', [tile1], 0, 0);
                this.groundLayer = groundLayer;
                this.wallLayer = wallLayer;
                decorationsLayer = this.map.createStaticLayer('decorations', [tile2], 0, 0);
                player = this.map.findObject('objects', function (obj) {
                  return obj.name === 'player';
                }); // get customer property by gid

                playerTileset = this.map.tilesets.find(function (ts) {
                  return ts.firstgid <= player.gid && ts.firstgid + ts.total > player.gid;
                });
                playerTile = playerTileset.tileProperties[player.gid - playerTileset.firstgid];
                pigs = this.map.filterObjects('objects', function (obj) {
                  return obj.name === 'pig';
                });
                groundLayer.setCollisionByProperty({
                  collides: true
                });
                wallLayer.setCollisionByProperty({
                  collides: true
                });
                this.objectives = this.add.group(); // random pig location
                // this.objectives.addMultiple(pigs.map(
                //   o =>
                //     new Objective({
                //       scene: this,
                //       key: 'pig',
                //       x: o.x,
                //       y: o.y-256,
                //     })
                // ))

                (0, _firestore.doc)(_firebaseApp["default"].firestore().collection('room').doc(roomId), 'id').subscribe(function (snap) {
                  var room = snap.data();

                  if (_this2.oldObjectives.length === 0 || _this2.oldObjectives.length > 0 && room.objectives.length > 0 && _this2.oldObjectives[0].x !== room.objectives[0].x && _this2.oldObjectives[0].y !== room.objectives[0].y) {
                    var objectives = (room.objectives || []).map(function (objective) {
                      return new _Objective["default"]({
                        scene: _this2,
                        key: 'pig',
                        x: objective.x,
                        y: objective.y
                      });
                    });
                    _this2.oldObjectives = room.objectives; // this.objectives.getChildren().map(o => {
                    //   o.setAlpha(0)
                    //   o.destroy()
                    // })

                    _this2.objectives.addMultiple(objectives);
                  }
                });

                if (!this.adminMode) {
                  this.player = new _Player["default"]({
                    scene: this,
                    key: 'boySprite',
                    x: player.x,
                    y: player.y - 256,
                    direction: playerTile ? playerTile.direction : 'right',
                    playerId: playerId,
                    playerName: playerName
                  }); // this.physics.add.collider(this.player.container, groundLayer)
                  // this.physics.add.collider(this.player.container, wallLayer)

                  this.cameras.main.startFollow(this.player.container, true, 0.1, 0.1, -128, -128);
                  this.add.text(16, 120, 'Score', {
                    fontSize: '126px',
                    fill: '#000000'
                  }).setScrollFactor(0);
                  this.messageScore = this.add.text(450, 120, this.score, {
                    fontSize: '126px',
                    fill: '#000000'
                  }).setScrollFactor(0);
                } else {
                  this.cameras.main.setZoom(0.5);
                  this.cameras.main.setScroll(2200, 3000);
                } // this.add.text(16, 20, 'Level', { fontSize: '126px', fill: '#000000' }).setScrollFactor(0)
                // this.messageLevel = this.add.text(450, 20, this.level, { fontSize: '126px', fill: '#000000' }).setScrollFactor(0)


                if (!this.adminMode) {
                  this.messageSkip = this.add.text(this.game.config.width - 20, 20, 'Retry', {
                    fontSize: '126px',
                    fill: '#000000'
                  }).setScrollFactor(0).setOrigin(1, 0).setInteractive().on('pointerdown', this.restart);
                }

                this.input.on('pointerdown', function (pointer) {
                  _this2.kineticScrolling.beginMove(pointer);

                  _this2.cameras.main.stopFollow();
                });
                this.input.on('pointerup', function () {
                  _this2.kineticScrolling.endMove();

                  _this2.timer = setTimeout(function () {
                    if (!_this2.adminMode) {
                      _this2.cameras.main.startFollow(_this2.player.container, true, 0.1, 0.1, -128, -128);
                    }
                  }, 1000);
                });
                this.input.on('pointermove', function (pointer) {
                  if (_this2.kineticScrolling.pointerId !== null) {
                    clearTimeout(_this2.timer);
                  }

                  _this2.kineticScrolling.move(pointer, pointer.x, pointer.y);
                });
                playerQuery = _firebaseApp["default"].firestore().collection('room').doc(roomId).collection('players').where('online', '==', true);
                this.players = this.add.group();
                (0, _firestore.collectionData)(playerQuery, 'id').subscribe(function (players) {
                  players.forEach(function (p) {
                    var hasPlayer = _this2.players.children.entries.find(function (o) {
                      return o.playerId === p.id;
                    });

                    if (!hasPlayer && _this2.game.playerId !== p.id) {
                      console.log(p);
                      var newPlayer = new _Player["default"]({
                        scene: _this2,
                        key: 'boySprite',
                        x: player.x,
                        y: player.y,
                        direction: playerTile ? playerTile.direction : 'right',
                        playerId: p.id,
                        playerName: p.playerName || p.id
                      });
                      newPlayer.setAlpha(0.5);

                      _this2.players.add(newPlayer);
                    }
                  });
                });

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

      function create() {
        return _create.apply(this, arguments);
      }

      return create;
    }()
  }, {
    key: "update",
    value: function update(time, delta) {
      this.keys = {
        up: this.input.keyboard.addKey(_phaser["default"].Input.Keyboard.KeyCodes.UP),
        left: this.input.keyboard.addKey(_phaser["default"].Input.Keyboard.KeyCodes.LEFT),
        right: this.input.keyboard.addKey(_phaser["default"].Input.Keyboard.KeyCodes.RIGHT),
        down: this.input.keyboard.addKey(_phaser["default"].Input.Keyboard.KeyCodes.DOWN)
      };

      if (!this.adminMode) {
        this.player && this.player.update(time, delta, this.keys);
      }

      this.objectives && this.objectives.children && this.objectives.children.entries.forEach(function (objective) {
        return objective.update(time, delta);
      });
      this.players && this.players.children && this.players.children.entries.forEach(function (objective) {
        return objective.update(time, delta);
      });
    }
  }]);

  return GameScene;
}(_phaser["default"].Scene);

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