"use strict";

require("core-js/modules/es.object.assign.js");

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

require("core-js/modules/web.dom-collections.iterator.js");

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

var _clone_player = _interopRequireDefault(require("../player/clone_player"));

var THREE = _interopRequireWildcard(require("three"));

var _fiber = require("@react-three/fiber");

var _drei = require("@react-three/drei");

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

var _fid = _interopRequireDefault(require("./fid.json"));

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

class StateAction {
  constructor() {
    var fc;
    Object.defineProperty(this, 'state', {
      get() {
        return fc === undefined ? false : fc;
      },

      set(v) {
        fc = v;
      }

    });
  }

}

class StateEmoji {
  constructor() {
    var fc;
    Object.defineProperty(this, 'state', {
      get() {
        return fc === undefined ? false : fc;
      },

      set(v) {
        fc = v;
      }

    });
  }

}

let nonPlayerInfos = [];
const ActionIcon = ["Emotion_001_Happy", "Emotion_002_Sad", "Emotion_003_Cry", "Emotion_004_Think", "Emotion_005_Angry", "Emotion_006_Angry2", "Emotion_007_Pout", "Emotion_008_Wow", "Emotion_009_Impress", "Emotion_010_Exciting2", "Emotion_011_OK", "Gestures_001_Swasdee", "Gestures_002_Swasdee", "Gestures_003_Kiss", "Gestures_004_Kiss", "Gestures_005_Float_Idle", "Gestures_006_Flex", "Waving01", "Waving02", "Waving03", "Chicken_Dance", "Dancing_Twerk", "Dancing_Running_Man", "Hip_Hop_Dance", "Step_Hip_Hop_Dance", "Tut_Hip_Hop_Dance"];
const tmpOffset1 = new THREE.Vector3();
const tmpOffset2 = new THREE.Vector3();
let tmptrack = [];
let cachedSelfData = null;

function randomIntFromInterval(min, max) {
  // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);
}

const PlayerPage = _ref => {
  let {
    socketController,
    callback,
    bot,
    track,
    chat
  } = _ref;
  const [clients, setClients] = (0, _react.useState)([]);
  (0, _react.useEffect)(() => {
    if (track) {
      tmptrack = track;
    }
  }, [track]);
  (0, _react.useEffect)(() => {
    if (bot) {
      for (let index = 0; index < bot; index++) {
        const obj = {
          playerId: _fid.default.RECORDS[index].fid,
          statePlayer: new StateAction(),
          position: new THREE.Vector3(randomIntFromInterval(-10, 10), 0, randomIntFromInterval(-10, 10)),
          quaternion: new THREE.Quaternion(0, 0, 0, 0),
          emojiIcon: new StateEmoji()
        };
        obj.statePlayer.state = ActionIcon[randomIntFromInterval(0, 25)];
        nonPlayerInfos.push(obj);
        setClients([...clients, obj]);
      }
    }
  }, [bot]);

  const adjustAudioVolume = (cachedPublisherData, remoteAudioTrack) => {
    tmpOffset1.set(cachedPublisherData[2][0], cachedPublisherData[2][1], cachedPublisherData[2][2]);
    tmpOffset2.set(cachedSelfData[2][0], cachedSelfData[2][1], cachedSelfData[2][2]);
    const soundDistance = tmpOffset1.distanceTo(tmpOffset2);
    const newVolume = 100 - soundDistance * 7; // console.log("Volume::",soundDistance,newVolume);

    if (soundDistance > 12 || newVolume <= 0) {
      var _remoteAudioTrack$_au;

      remoteAudioTrack === null || remoteAudioTrack === void 0 ? void 0 : (_remoteAudioTrack$_au = remoteAudioTrack._audioTrack) === null || _remoteAudioTrack$_au === void 0 ? void 0 : _remoteAudioTrack$_au.setVolume(0);
    } else {
      var _remoteAudioTrack$_au2;

      remoteAudioTrack === null || remoteAudioTrack === void 0 ? void 0 : (_remoteAudioTrack$_au2 = remoteAudioTrack._audioTrack) === null || _remoteAudioTrack$_au2 === void 0 ? void 0 : _remoteAudioTrack$_au2.setVolume(newVolume);
    }
  };

  const handlePlayerUpdate = (data, nodeId) => {
    data.forEach(updatedData => {
      //audio distance
      if (tmptrack) {
        const remoteAudioTrack = _lodash.default.find(tmptrack, {
          'uid': updatedData[0]
        }); // console.log(remoteAudioTrack , cachedSelfData);


        if (remoteAudioTrack && cachedSelfData) {
          adjustAudioVolume(updatedData, remoteAudioTrack);
        }
      } // update position and quaternion from channel server
      // do not update in case of all update to prevent double update


      const nonPlayerInfo = _lodash.default.find(nonPlayerInfos, {
        'playerId': updatedData[0]
      }); // console.log(updatedData);


      if (nonPlayerInfo) {
        nonPlayerInfo.statePlayer.state = updatedData[1];
        nonPlayerInfo.position.set(updatedData[2][0], updatedData[2][1], updatedData[2][2]);
        nonPlayerInfo.quaternion.set(updatedData[3][0], updatedData[3][1], updatedData[3][2], updatedData[3][3]);
        nonPlayerInfo.emojiIcon.state = updatedData[4];
      } else {
        // create if never seen before
        if (socketController.playerId !== updatedData[0]) {
          console.count('new player ::');
          const obj = {
            nodeId: nodeId,
            playerId: updatedData[0],
            statePlayer: new StateAction(),
            position: new THREE.Vector3(updatedData[2][0], updatedData[2][1], updatedData[2][2]),
            quaternion: new THREE.Quaternion(updatedData[3][0], updatedData[3][1], updatedData[3][2], updatedData[3][3]),
            emojiIcon: new StateEmoji()
          };
          nonPlayerInfos.push(obj);
          setClients([...clients, obj]);
        }
      }
    });
  };

  const handleChannelUpdate = (updatedDatas, nodeId) => {
    // console.log('handleChannelUpdate from nodeId: '+nodeId)
    for (let nonPlayerInfoIndex = nonPlayerInfos.length - 1; nonPlayerInfoIndex >= 0; nonPlayerInfoIndex--) {
      const nonPlayerInfo = nonPlayerInfos[nonPlayerInfoIndex];

      if (nonPlayerInfo.nodeId * 1 !== nodeId * 1) {
        // not from the same node
        // can be ignore
        continue;
      }

      const updatedData = updatedDatas.find(updatedDt => updatedDt[0] === nonPlayerInfo.playerId); // remove if already left the room

      if (!updatedData) {
        console.count('delete player ::');
        nonPlayerInfos.splice(nonPlayerInfoIndex, 1);
        setClients(nonPlayerInfos);
      }
    }
  };

  (0, _react.useEffect)(() => {
    socketController.socket.on('verse.channel.update', (event, nodeId) => {
      const SelfData = event.find(a => a[0] === socketController.playerId);

      if (SelfData) {
        cachedSelfData = SelfData;
      }

      handlePlayerUpdate(event, nodeId, track);
    });
    socketController.socket.on('verse.channel.update.all', (event, nodeId) => {
      handleChannelUpdate(event, nodeId);
    });
  }, []);
  return /*#__PURE__*/_react.default.createElement("group", null, nonPlayerInfos.map((i, index) => /*#__PURE__*/_react.default.createElement(_clone_player.default, _extends({
    socketClient: socketController,
    key: i.playerId,
    callback: callback,
    chat: chat
  }, i))));
}; // useGLTF.preload(`${characters.path}/main/${characters.base}`)


var _default = PlayerPage;
exports.default = _default;