"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"));

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), "nextLevel", function () {
      // check level
      var mapInfo;
      var nextLevel = _this.level + 1;

      if (nextLevel > 8) {
        nextLevel = 1;
      }

      _this.scene.restart({
        level: nextLevel,
        score: 0
      });
    });

    _defineProperty(_assertThisInitialized(_this), "calculateTime", function () {
      var secondLeft = Math.floor((_this.timeConfig - _this.timer.getElapsed()) / 1000);
      var second = secondLeft % 60 || 0;
      var minute = Math.floor(secondLeft / 60) || 0;
      return {
        minute: minute,
        second: second
      };
    });

    _defineProperty(_assertThisInitialized(_this), "tick", function () {
      _this.seconds++;
    });

    return _this;
  }

  _createClass(GameScene, [{
    key: "init",
    value: function init(_ref) {
      var level = _ref.level,
          score = _ref.score;
      this.level = level;
      this.score = score || 0;
      this.game.events.emit('setLevel', level);
      this.seconds = 0;
    }
  }, {
    key: "preload",
    value: function 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({
        level: this.level,
        score: 0
      });
    }
  }, {
    key: "create",
    value: function () {
      var _create = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee() {
        var _this2 = this;

        var mapInfo, mapData, tile1, tile2, groundLayer, wallLayer, decorationsLayer, player, playerTileset, playerTile, pigs;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                // this.game.kineticScrolling.start();
                this.kineticScrolling = new _KineticScroll["default"](this);
                mapData = _phaser["default"].Tilemaps.Parsers.Parse('map', _phaser["default"].Tilemaps.Formats.TILED_JSON, require("../assets/map".concat(this.level, ".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);
                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();
                this.objectives.addMultiple(pigs.map(function (o) {
                  return new _Objective["default"]({
                    scene: _this2,
                    key: 'pig',
                    x: o.x,
                    y: o.y - 256
                  });
                }));
                this.player = new _Player["default"]({
                  scene: this,
                  key: 'boySprite',
                  x: player.x,
                  y: player.y - 256,
                  direction: playerTile ? playerTile.direction : 'right'
                });
                this.physics.add.collider(this.player, groundLayer);
                this.physics.add.collider(this.player, wallLayer);
                this.add.text(16, 20, 'Level', {
                  fontSize: '126px',
                  fill: '#000000'
                }).setScrollFactor(0);
                this.add.text(16, 120, 'Score', {
                  fontSize: '126px',
                  fill: '#000000'
                }).setScrollFactor(0);
                this.messageLevel = this.add.text(450, 20, this.level, {
                  fontSize: '126px',
                  fill: '#000000'
                }).setScrollFactor(0);
                this.messageScore = this.add.text(450, 120, this.score, {
                  fontSize: '126px',
                  fill: '#000000'
                }).setScrollFactor(0);
                this.messageSkip = this.add.text(this.game.config.width - 20, 20, 'Skip', {
                  fontSize: '126px',
                  fill: '#000000'
                }).setScrollFactor(0).setOrigin(1, 0).setInteractive().on('pointerdown', this.nextLevel);
                this.cameras.main.startFollow(this.player, true, 0.1, 0.1, -128, -128);
                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 () {
                    _this2.cameras.main.startFollow(_this2.player, 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);
                }); // setup timer

                this.time.addEvent({
                  delay: 1000,
                  callback: this.tick,
                  callbackScope: this,
                  loop: true
                });

              case 29:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, 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)
      };
      this.player.update(time, delta, this.keys);
      this.objectives.children.entries.forEach(function (objective) {
        return objective.update(time, delta);
      });
    }
  }]);

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

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