'use strict';

var types_did_onchain_typedDid_didMethodKey_didMethodKeyPublicKey = require('./did-method-key/did-method-key-public-key.cjs');
require('./did-method-key/did-method-key-signature.cjs');
var types_did_onchain_typedDid_dockDidValue = require('./dock-did-value.cjs');
var types_generic_typedEnum = require('../../../generic/typed-enum.cjs');
require('../../../generic/typed-bytes.cjs');
require('../../../generic/typed-string.cjs');
require('../../../generic/typed-array.cjs');
var types_generic_typedTuple = require('../../../generic/typed-tuple.cjs');
require('../../../generic/typed-null.cjs');
require('../../../../utils/types/array.cjs');
var utils_types_bytes = require('../../../../utils/types/bytes.cjs');
var utils_inheritance = require('../../../../utils/inheritance.cjs');
require('bs58');
require('multiformats/bases/base58');
require('varint');
require('../../../../utils/encoding/ss-58.cjs');
require('../../../generic/typed-number.cjs');
require('../../../generic/typed-set.cjs');
require('../../../generic/typed-map.cjs');
require('../../../generic/typed-struct.cjs');
var types_generic_typedUuid = require('../../../generic/typed-uuid.cjs');
var types_generic_withQualifier = require('../../../generic/with-qualifier.cjs');
var types_generic_utils = require('../../../generic/utils.cjs');
var types_did_onchain_typedDid_cheqdDid = require('./cheqd-did.cjs');
var types_did_onchain_typedDid_signature = require('./signature.cjs');
require('../../../../utils/encoding/base-58-btc.cjs');
require('../../../../utils/types/string.cjs');
require('../../../../utils/error.cjs');
require('../../../generic/sized.cjs');
require('../../../../utils/types/number.cjs');
require('crypto');
require('uuid');
require('js-sha256');
require('../../../public-keys/public-key.cjs');
require('../../../public-keys/public-key-x25519-value.cjs');
require('../../../public-keys/public-key-ed25519-value.cjs');
require('../../../../vc/crypto/constants.cjs');
require('../../../public-keys/public-key-secp256k1-value.cjs');
require('../../../public-keys/public-key-sr25519-value.cjs');
require('../constants.cjs');
require('../../../signatures/signature-value.cjs');
require('../../../signatures/signature-ed25519-value.cjs');
require('../../../signatures/signature-secp256k1-value.cjs');
require('../../../signatures/signature.cjs');
require('../../../signatures/signature-sr25519-value.cjs');
require('../../../../utils/types/iterable.cjs');
require('../../../../utils/types/object.cjs');
require('../../../../utils/interfaces.cjs');
require('../../../../utils/assert.cjs');
require('../../../generic/with-base.cjs');
require('../../../generic/with-catch-null.cjs');
require('../../../generic/with-eq.cjs');
require('../../../generic/any-of.cjs');
require('../../../generic/with-from.cjs');
require('../../../generic/with-from-json-bytes.cjs');
require('../../../generic/create-placeholder.cjs');
require('../../../../utils/types/set.cjs');
require('blake2b');
require('../../../generic/typed-bytes-array.cjs');

class DockDidOrDidMethodKey extends types_generic_withQualifier(types_generic_typedEnum, true) {
  /**
   * Instantiates a random `dock:did:*`.
   */
  static random() {
    return new this(this.Class.random());
  }

  signWith(keyPair, bytes) {
    return this.value.signWith(keyPair, bytes);
  }

  /**
   * Creates signature for the state change with supplied arguments.
   *
   * @param apiProvider
   * @param name
   * @param payload
   * @param keyRef
   * @returns {object}
   */
  async signStateChange(apiProvider, name, payload, keyRef) {
    const { LOG_STATE_CHANGE } = process.env;
    if (Number(LOG_STATE_CHANGE) || Boolean(LOG_STATE_CHANGE)) {
      console.dir(payload, { depth: null });
    }
    const bytes = await apiProvider.stateChangeBytes(name, payload);

    return this.signWith(keyRef, bytes);
  }

  /**
   * Creates a transaction that will modify the chain state.
   *
   * @param api
   * @param method
   * @param name
   * @param payload
   * @param keyRef
   */
  async changeState(api, method, name, payload, keyRef) {
    return await method(
      payload,
      await this.signStateChange(api, name, payload, keyRef),
    );
  }

  toString() {
    return String(this.value);
  }

  static fromApi(value) {
    if (value.isDock) {
      return super.from(value.asDock);
    } else {
      return super.fromApi(value);
    }
  }

  static fromJSON(json) {
    if (json?.dock) {
      return super.fromJSON({ did: json?.dock });
    } else {
      return super.fromJSON(json);
    }
  }

  static from(value) {
    if (utils_types_bytes.isHexWithGivenByteSize(String(value), 32)) {
      // eslint-disable-next-line no-use-before-define
      return new DockDid(value);
    }

    // eslint-disable-next-line no-use-before-define
    if (value instanceof NamespaceDid) {
      return super.from(value.isDock ? { did: value.asDock } : value);
    } else {
      return super.from(value);
    }
  }
}

class DockDid extends DockDidOrDidMethodKey {
  static Class = types_did_onchain_typedDid_dockDidValue.default;

  toHex() {
    return this.value.toHex();
  }

  toQualifiedString() {
    return this.value.toQualifiedString();
  }
}

class DidMethodKey extends DockDidOrDidMethodKey {
  static Class = types_did_onchain_typedDid_didMethodKey_didMethodKeyPublicKey.DidMethodKeyPublicKey;

  static fromKeypair(keypair) {
    return new this(types_did_onchain_typedDid_didMethodKey_didMethodKeyPublicKey.DidMethodKeyPublicKey.fromKeypair(keypair));
  }
}

DockDidOrDidMethodKey.bindVariants(DockDid, DidMethodKey);

class NamespaceDid extends types_generic_withQualifier(types_generic_typedEnum, true) {
  toCheqdPayload() {
    return String(this);
  }

  toJSON() {
    return String(this);
  }

  static fromApi(value) {
    if (value.isDid) {
      return super.from({ dock: value.asDid });
    } else {
      return super.fromApi(value);
    }
  }

  static fromJSON(json) {
    if (json?.did && Object.keys(json).length === 1) {
      return super.fromJSON({ dock: json.did });
    } else {
      return super.fromJSON(json);
    }
  }

  static from(value) {
    return super.from(
      value instanceof DockDidOrDidMethodKey && value.isDid
        ? { dock: value.asDid }
        : value,
    );
  }
}

class DockNamespaceDid extends NamespaceDid {
  static Qualifier = 'did:dock:';

  static Type = 'dock';

  static Class = types_did_onchain_typedDid_dockDidValue.default;
}
class DidNamespaceKey extends NamespaceDid {
  static Qualifier = 'did:key:';

  static Type = 'didMethodKey';

  static Class = types_did_onchain_typedDid_didMethodKey_didMethodKeyPublicKey.DidMethodKeyPublicKey;
}
class CheqdNamespaceDid extends NamespaceDid {
  static Qualifier = 'did:cheqd:';

  static Type = 'cheqd';

  static Class = types_did_onchain_typedDid_cheqdDid.CheqdDid;
}

NamespaceDid.bindVariants(DockNamespaceDid, DidNamespaceKey, CheqdNamespaceDid);

for (const Class of [types_did_onchain_typedDid_cheqdDid.CheqdTestnetDid, types_did_onchain_typedDid_cheqdDid.CheqdMainnetDid]) {
  const fromFn = Class.from;

  Class.from = function from(value) {
    try {
      return new this(
        types_generic_typedUuid.fromDockIdent(DockNamespaceDid.from(value), 'did:cheqd:'),
      );
    } catch {
      return fromFn.call(this, value);
    }
  };
}

class DidRef extends utils_inheritance.withExtendedStaticProperties(
  ['Ident'],
  types_generic_withQualifier(types_generic_typedTuple),
) {
  static Qualifier = '';

  static Did = NamespaceDid;

  static get Classes() {
    return [this.Did, this.Ident];
  }

  static random(did) {
    return new this(did, this.Ident.random());
  }

  get did() {
    return this[0];
  }

  get value() {
    return this[1];
  }

  static fromUnqualifiedString(str) {
    const regex = new RegExp(`^${this.Qualifier}([^#]+):(.+)$`);
    const match = str.match(regex);

    if (!match) {
      throw new Error(`Invalid format for DID reference: \`${str}\``);
    }

    const [, did, value] = match;
    return new this(did, value);
  }

  toEncodedString() {
    const { did, value } = this;

    return `${did}:${value}`;
  }

  toJSON() {
    return String(this);
  }
}

class CheqdDidRef extends types_generic_withQualifier(DidRef) {
  static Did = types_did_onchain_typedDid_cheqdDid.CheqdDid;

  static fromUnqualifiedString(str) {
    const lastColon = str.lastIndexOf(':');
    const did = `did:cheqd:${str.slice(0, lastColon)}`;
    const id = str.slice(lastColon + 1);

    return new this(did, id);
  }

  toJSON() {
    return String(this);
  }

  toEncodedString() {
    const { did, value } = this;

    let prefix = '';
    if (did.isTestnet) {
      prefix = 'testnet';
    } else if (did.isMainnet) {
      prefix = 'mainnet';
    } else {
      throw new Error(
        `Can't determine DID type: \`${did}\`, instance of \`${did.constructor.name}\``,
      );
    }

    return `${prefix}:${did.toEncodedString()}:${value}`;
  }
}

types_did_onchain_typedDid_signature.bindVariants(
  types_did_onchain_typedDid_dockDidValue.DockDidSignature,
  types_did_onchain_typedDid_didMethodKey_didMethodKeyPublicKey.DidMethodKeySignature,
);

/**
 * Retrieve all possible stringified representations of DIDs that can be derived from the provided Dock DID.
 *
 * @param {*} did
 * @returns {Array<string>}
 */
const possibleDids = types_generic_utils.createConverter(
  String,
  DockDid,
  types_did_onchain_typedDid_cheqdDid.CheqdTestnetDid,
  types_did_onchain_typedDid_cheqdDid.CheqdMainnetDid,
);

exports.DidMethodKeyPublicKey = types_did_onchain_typedDid_didMethodKey_didMethodKeyPublicKey.DidMethodKeyPublicKey;
exports.DockDidValue = types_did_onchain_typedDid_dockDidValue.default;
exports.CheqdDLRRef = types_did_onchain_typedDid_cheqdDid.CheqdDLRRef;
exports.CheqdDid = types_did_onchain_typedDid_cheqdDid.CheqdDid;
exports.CheqdDidValue = types_did_onchain_typedDid_cheqdDid.CheqdDidValue;
exports.CheqdMainnetDid = types_did_onchain_typedDid_cheqdDid.CheqdMainnetDid;
exports.CheqdMainnetDidValue = types_did_onchain_typedDid_cheqdDid.CheqdMainnetDidValue;
exports.CheqdTestnetDid = types_did_onchain_typedDid_cheqdDid.CheqdTestnetDid;
exports.CheqdTestnetDidValue = types_did_onchain_typedDid_cheqdDid.CheqdTestnetDidValue;
exports.CheqdDidRef = CheqdDidRef;
exports.CheqdNamespaceDid = CheqdNamespaceDid;
exports.DidMethodKey = DidMethodKey;
exports.DidNamespaceKey = DidNamespaceKey;
exports.DidRef = DidRef;
exports.DockDid = DockDid;
exports.DockDidOrDidMethodKey = DockDidOrDidMethodKey;
exports.DockNamespaceDid = DockNamespaceDid;
exports.NamespaceDid = NamespaceDid;
exports.possibleDids = possibleDids;
//# sourceMappingURL=index.cjs.map
