//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { VmmCmdType } from '@/model/base-enum';

export const packVmm = {

   /**
   * vmm消息格式定义，命名规则如下
   * @param opcode 消息类型（操作码）
   * @param status 操作状态码
   * @param sack 描述失败原因
   * @param seq 序列号，表示消息跟哪个CWB包对应
   * @param dataLength 数据长度
   * @param data 消息体
   * 消息格式定义：消息类型(1B)+操作状态码(1B)+失败原因(1B)+序列号(1B)+数据长度(4B)+消息体
   */
  packageData(opcode: number, bodyData: number[] = [], status: number = 0, sack: number = 0, seq: number = 0) {
    const packetedData = new Uint8Array(bodyData.length + 8);
    packetedData[0] = opcode & 0xff;
    packetedData[1] = status & 0xff;
    packetedData[2] = sack & 0xff;
    packetedData[3] = seq & 0xff;
    packetedData[4] = (bodyData.length & 0xff000000) >> 24;
    packetedData[5] = (bodyData.length & 0xff0000) >> 16;
    packetedData[6] = (bodyData.length & 0xff00) >> 8;
    packetedData[7] = bodyData.length & 0xff;
    bodyData.forEach((item, index) => packetedData[8 + index] = item);
    return packetedData;
  },
  parseRspData(data: Uint8Array) {
    const result = {
      opcode: 0,
      status: 0,
      sack: 0,
      seq: 0,
      dataLength: 0,
      bodyData: null as any,
    };
    // 确保获取的消息正确：有消息头(8位)
    if (data.length >= 8) {
      result.opcode = data[0];
      result.status = data[1];
      result.sack = data[2];
      result.seq = data[3];
      result.dataLength = (data[4] << 24) + (data[5] << 16) + (data[6] << 8) + data[7];
      const responseBody = [...data].slice(8);
      if (responseBody.length === result.dataLength ) {
        result.bodyData = responseBody;
      }
    }
    return result;
  },
  // 连接vmm服务
  packConnect(bodyData: number[]) {
    return packVmm.packageData(VmmCmdType.CONNECT, bodyData);
  },
  // 断开Vmm连接
  packDisconnect() {
    return packVmm.packageData(VmmCmdType.DISCONNECT);
  },
  packHeartBeat() {
    return packVmm.packageData(VmmCmdType.HEARTBEAT);
  },
  packCreateVirtualDev(bodyData: number = 0) {
    return packVmm.packageData(VmmCmdType.CREATE_DEV, [bodyData]);
  },
  packDISCVirtualDev(bodyData: number = 0) {
    return packVmm.packageData(VmmCmdType.CLOSE_DEV, [bodyData]);
  }
};