import { ENCRYPTED_REFERENCE_BYTES_LENGTH, ENCRYPTED_REFERENCE_HEX_LENGTH, REFERENCE_BYTES_LENGTH, REFERENCE_HEX_LENGTH } from "../types/index.js";
import { bytesAtOffset, hasBytesAtOffset } from "./bytes.js";
import { hexToBytes, makeHexString } from "./hex.js";
export function makeBytesReference(reference, offset = 0) {
  if (typeof reference === 'string') {
    if (offset) {
      throw new Error('Offset property can be set only for UintArray reference!');
    }

    try {
      // Non-encrypted chunk hex string reference
      const hexReference = makeHexString(reference, REFERENCE_HEX_LENGTH);
      return hexToBytes(hexReference);
    } catch (e) {
      if (!(e instanceof TypeError)) {
        throw e;
      } // Encrypted chunk hex string reference


      const hexReference = makeHexString(reference, ENCRYPTED_REFERENCE_HEX_LENGTH);
      return hexToBytes(hexReference);
    }
  } else if (reference instanceof Uint8Array) {
    if (hasBytesAtOffset(reference, offset, ENCRYPTED_REFERENCE_BYTES_LENGTH)) {
      return bytesAtOffset(reference, offset, ENCRYPTED_REFERENCE_BYTES_LENGTH);
    } else if (hasBytesAtOffset(reference, offset, REFERENCE_BYTES_LENGTH)) {
      return bytesAtOffset(reference, offset, REFERENCE_BYTES_LENGTH);
    }
  }

  throw new TypeError('invalid chunk reference');
}