import { Buff } from '@cmdcode/buff';
import { Signer, Wallet } from '@cmdcode/signer';
import { EscrowClient } from './client.js';
import deposit_api from '../api/depositor.js';
import endorse_api from '../api/endorse.js';
import request_api from '../api/request.js';
import { claim_membership_api, gen_membership_api, has_membership_api } from '../../client/api/member.js';
const DEFAULT_IDXGEN = () => Buff.now(4).num;
export class EscrowSigner {
    static load(password, payload) {
        const bytes = Buff.bech32(payload);
        const encdata = bytes.subarray(0, 96);
        const xpub = bytes.subarray(96).b58chk;
        const pass = Buff.str(password);
        const signer = Signer.restore(pass, encdata);
        const wallet = new Wallet(xpub);
        return new EscrowSigner({ signer, wallet });
    }
    constructor(config) {
        this.deposit = deposit_api(this);
        this.endorse = endorse_api(this);
        this.request = request_api(this);
        this.gen_membership = gen_membership_api(this);
        this.get_membership = claim_membership_api(this);
        this.has_membership = has_membership_api(this);
        this._client = new EscrowClient(config);
        this._gen_idx = config.idxgen ?? DEFAULT_IDXGEN;
        this._signer = config.signer;
        this._wallet = config.wallet;
    }
    get client() {
        return this._client;
    }
    get pubkey() {
        return this._signer.pubkey;
    }
    save(password) {
        const pass = Buff.str(password);
        const encdata = this._signer.backup(pass);
        const xbytes = Buff.b58chk(this._wallet.xpub);
        const payload = Buff.join([encdata, xbytes]);
        return payload.to_bech32('cred');
    }
}
