"use strict";

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

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

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

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

var _GameScene = _interopRequireDefault(require("./GameScene"));

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

  function RoomAdminScene() {
    var _this;

    _classCallCheck(this, RoomAdminScene);

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

    _defineProperty(_assertThisInitialized(_this), "addPlayerScore", function (playerId, score) {
      console.log('add player score');

      if (!_this.players[playerId]) {
        return;
      }

      _this.setPlayerScore(playerId, (_this.players[playerId].score || 0) + 1);
    });

    _defineProperty(_assertThisInitialized(_this), "setPlayerScore", function (playerId, score) {
      console.log('add player score');
      _this.players[playerId].score = score;

      _this.players[playerId].scoreLabel.setText(score);
    });

    _defineProperty(_assertThisInitialized(_this), "handleNextRound",
    /*#__PURE__*/
    _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee() {
      var ref, batch;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              ref = function ref(playerId) {
                return _firebaseApp["default"].firestore().collection('room').doc(_this.roomId).collection('players').doc(playerId);
              };

              batch = _firebaseApp["default"].firestore().batch();
              batch.set(_firebaseApp["default"].firestore().collection('room').doc(_this.roomId), {
                complete: true
              }, {
                merge: true
              });
              Object.keys(_this.players).forEach(function (playerId) {
                batch.set(ref(playerId), {
                  score: _this.players[playerId].score || 0
                }, {
                  merge: true
                });
              });
              _context.next = 6;
              return batch.commit();

            case 6:
              console.log('commited');

              _this.scene.get('GameScene').restart();

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

    _defineProperty(_assertThisInitialized(_this), "addPlayer", function (playerId, playerName) {
      var y = Object.keys(_this.players).length * 100;

      if (!_this.players[playerId]) {
        var label = _this.add.text(0, y, playerName || playerId, {
          fontSize: '64px',
          fill: '#000000',
          fixedWidth: 500
        }).setOrigin(0, 0);

        var scoreLabel = _this.add.text(540, y, 0, {
          fontSize: '64px',
          fill: '#000000'
        }).setOrigin(0, 0);

        _this.topLeftContainer.add(label);

        _this.topLeftContainer.add(scoreLabel);

        _this.players[playerId] = {
          scoreLabel: scoreLabel,
          score: 0
        };
        (0, _firestore.doc)(_firebaseApp["default"].firestore().collection('room').doc(_this.roomId).collection('players').doc(playerId)).subscribe(function (snap) {
          var player = snap.data();

          if (!_this.previousPlayer[playerId] || _this.previousPlayer[playerId].score !== player.score) {
            _this.setPlayerScore(playerId, player.score);
          }

          _this.previousPlayer[playerId] = player;
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleRestart",
    /*#__PURE__*/
    _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee2() {
      var ref, batch;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              ref = function ref(playerId) {
                return _firebaseApp["default"].firestore().collection('room').doc(_this.roomId).collection('players').doc(playerId);
              };

              batch = _firebaseApp["default"].firestore().batch();
              Object.keys(_this.players).forEach(function (playerId) {
                batch.set(ref(playerId), {
                  running: false
                }, {
                  merge: true
                });
              });
              _context2.next = 5;
              return batch.commit();

            case 5:
              console.log('commited');

              _this.scene.get('GameScene').restart();

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

    _defineProperty(_assertThisInitialized(_this), "handleRun",
    /*#__PURE__*/
    _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee3() {
      var snap, playersCode;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              // this.scene.get('GameScene').restart()
              console.log('run'); // get data

              _context3.next = 3;
              return _firebaseApp["default"].firestore().collection('room').doc(_this.roomId).collection('players').get();

            case 3:
              snap = _context3.sent;
              playersCode = snap.docs.reduce(function (result, doc) {
                var player = doc.data();
                var playerId = doc.id;
                return _objectSpread({}, result, _defineProperty({}, playerId, player.code));
              }, {});

              _this.scene.get('GameScene').players.children.entries.forEach(function (player) {
                console.log(player);
                player.runCode(playersCode[player.playerId]);
              });

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

    return _this;
  }

  _createClass(RoomAdminScene, [{
    key: "init",
    value: function init(_ref4) {
      var roomId = _ref4.roomId;
      this.players = {};
      this.previousPlayer = {};
      this.roomId = roomId;
    }
  }, {
    key: "preload",
    value: function preload() {}
  }, {
    key: "create",
    value: function create() {
      var _this2 = this;

      var width = this.game.config.width;
      var height = this.game.config.height;
      this.topLeftContainer = this.add.container(50, 50, []);
      this.topRightContainer = this.add.container(width - 300, 50, [this.add.container(0, 50, [this.add.image(0, 0, 'button').setDisplaySize(400, 100).setInteractive().on('pointerdown', this.handleRun), this.add.text(0, 0, 'Start', {
        fontSize: '64px',
        fill: '#ffffff'
      }).setOrigin(0.5, 0.5)]), this.add.container(0, 200, [this.add.image(0, 0, 'button').setDisplaySize(400, 100).setInteractive().on('pointerdown', this.handleRestart), this.add.text(0, 0, 'Restart', {
        fontSize: '64px',
        fill: '#ffffff'
      }).setOrigin(0.5, 0.5)]), this.add.container(0, 350, [this.add.image(0, 0, 'button').setDisplaySize(400, 100).setInteractive().on('pointerdown', this.handleNextRound), this.add.text(0, 0, 'Next round', {
        fontSize: '64px',
        fill: '#ffffff'
      }).setOrigin(0.5, 0.5)])]);
      (0, _firestore.collectionData)(_firebaseApp["default"].firestore().collection('room').doc(this.roomId).collection('players'), 'id').subscribe(function (players) {
        players.forEach(function (player) {
          _this2.addPlayer(player.id, player.playerName);
        });
      });
    }
  }]);

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

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