/* 一些MC服创建/加入房间相关的通用函数 */

import { Options } from "./options";

export interface Room {
  id?: string;
  title?: string;
  users?: { username: string; position: number; avatar?: string }[];
  options: Options;
}

// 通过房间ID和external_id加密得出房间密码
//
// 用于加入MC服房间
export function getEncryptedPasswd(
  roomID: string,
  external_id: number,
): string {
  const optionsBuffer = new Uint8Array(6);
  optionsBuffer[1] = 3 << 4;
  let checksum = 0;

  for (let i = 1; i < optionsBuffer.length; i++) {
    checksum -= optionsBuffer[i];
  }

  optionsBuffer[0] = checksum & 0xff;

  const secret = (external_id % 65535) + 1;

  for (let i = 0; i < optionsBuffer.length; i += 2) {
    const value = (optionsBuffer[i + 1] << 8) | optionsBuffer[i];
    const xorResult = value ^ secret;
    optionsBuffer[i + 1] = (xorResult >> 8) & 0xff;
    optionsBuffer[i] = xorResult & 0xff;
  }

  const base64String = btoa(String.fromCharCode(...optionsBuffer));

  return base64String + roomID;
}
