'use strict';

var uuid = require('uuid');
var jsSha256 = require('js-sha256');
var types_generic_typedBytes = require('./typed-bytes.cjs');
require('../../utils/types/array.cjs');
var utils_types_bytes = require('../../utils/types/bytes.cjs');
require('bs58');
require('multiformats/bases/base58');
require('varint');
require('../../utils/encoding/ss-58.cjs');
require('./with-base.cjs');
require('../../utils/interfaces.cjs');
require('../../utils/assert.cjs');
require('../../utils/error.cjs');
require('../../utils/inheritance.cjs');
require('../../utils/types/object.cjs');
require('../../utils/types/iterable.cjs');
require('../../utils/types/set.cjs');
require('./with-catch-null.cjs');
require('./with-eq.cjs');
require('./any-of.cjs');
require('crypto');
require('./with-from.cjs');
require('blake2b');
require('../../utils/types/string.cjs');
require('./with-from-json-bytes.cjs');

class TypedUUID extends types_generic_typedBytes {
  constructor(id) {
    if (typeof id === 'string') {
      if (!uuid.validate(id)) {
        throw new Error(`Invalid UUID: \`${id}\``);
      }

      super(uuid.parse(id));
    } else {
      super(id);
    }

    if (!uuid.validate(this.value)) {
      throw new Error(`Invalid UUID: ${this.value}`);
    }
  }

  get value() {
    return uuid.stringify(this.bytes);
  }

  toString() {
    return this.value;
  }

  toJSON() {
    return String(this);
  }

  static fromDockIdent(dockIdent, prefix = []) {
    const { CHEQD_MIGRATION_PREFIX } = process.env;

    let prefixBytes = utils_types_bytes.normalizeOrConvertStringToU8a(prefix);
    if (CHEQD_MIGRATION_PREFIX) {
      prefixBytes = [
        ...prefixBytes,
        ...utils_types_bytes.normalizeOrConvertStringToU8a(CHEQD_MIGRATION_PREFIX),
      ];
    }
    const identBytes = utils_types_bytes.valueNumberOrBytes(dockIdent);
    const hash = jsSha256.sha256.digest([...prefixBytes, ...identBytes]);

    return this.fromBytesAdapt(hash);
  }

  static fromBytesAdapt(bytesOrString) {
    let bytes = utils_types_bytes.normalizeOrConvertStringToU8a(bytesOrString);
    if (bytes.length < 16) {
      const newBytes = new Uint8Array(16);
      newBytes.set(bytes);
      newBytes.fill(0, bytes.length);

      bytes = newBytes;
    } else if (bytes.length > 16) {
      bytes = bytes.slice(0, 16);
    }

    // eslint-disable-next-line no-bitwise
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    // eslint-disable-next-line no-bitwise
    bytes[8] = (bytes[8] & 0x3f) | 0x80;

    return new this(bytes);
  }

  static random() {
    return new this(uuid.v4());
  }
}

module.exports = TypedUUID;
//# sourceMappingURL=typed-uuid.cjs.map
