/**
 * @file CGUpdateLeaderboard.js
 * @author Frank Hamilton
 * @date 2024/2/27
 * @brief CGUpdateLeaderboard.js
 * @copyright Copyright (c) 2023, ByteDance Inc, All Rights Reserved
 */

const {BaseNode} = require('../Utils/BaseNode');
const {LeaderboardDataStore} = require('../../../Plugins/LeaderboardDataStore');

const Amaz = effect.Amaz;
const LBSDS = LeaderboardDataStore.instance;

class CGUpdateLeaderboard extends BaseNode {
  constructor() {
    super();
  }

  setNext(index, func) {
    this.nexts[index] = func;
  }

  setInput(index, func) {
    this.inputs[index] = func;
  }

  execute(index) {
    if (index === 0) {
      if (!LBSDS) return;

      if (LBSDS.leaderboardReady === true) {
        LBSDS.setScore(this.inputs[2]());
        if (LBSDS.hasScore && LBSDS.currentRank_friends > LBSDS.friends_rank) {
          this.outputs[1] = LBSDS.currentRank_friends - 1;
        } else {
          this.outputs[1] = LBSDS.currentRank_friends;
        }

        if (LBSDS.hasScore && LBSDS.currentRank_national > LBSDS.national_rank) {
          this.outputs[2] = LBSDS.currentRank_national - 1;
        } else {
          this.outputs[2] = LBSDS.currentRank_national;
        }

        if (LBSDS.hasScore && LBSDS.currentRank_global > LBSDS.global_rank) {
          this.outputs[3] = LBSDS.currentRank_global - 1;
        } else {
          this.outputs[3] = LBSDS.currentRank_global;
        }

        if (this.nexts[0]) {
          this.nexts[0]();
        }
      }
    } else if (index === 1) {
      LBSDS.postScore();

      if (this.nexts[0]) {
        this.nexts[0]();
      }
    }
  }
}

exports.CGUpdateLeaderboard = CGUpdateLeaderboard;
