import { now, sleep } from '../../lib/util.js';
import { validate_contract } from '../../validators/contract.js';
import { EventEmitter } from './emitter.js';
import { ContractVM } from './machine.js';
const DEFAULT_CONFIG = {
    refresh_ival: 10,
    verbose: true
};
export class EscrowContract extends EventEmitter {
    static async create(client, draft, config) {
        const res = await client.contract.create(draft);
        if (!res.ok)
            throw new Error(res.error);
        const dat = res.data.contract;
        return new EscrowContract(client, dat, config);
    }
    static async fetch(client, cid, config) {
        const res = await client.contract.read(cid);
        if (!res.ok)
            throw new Error(res.error);
        const dat = res.data.contract;
        return new EscrowContract(client, dat, config);
    }
    constructor(client, contract, config) {
        super();
        this.moderator = {};
        this._client = client;
        this._opt = { ...DEFAULT_CONFIG, ...config };
        this._data = contract;
        this._updated = contract.updated_at;
    }
    get cid() {
        return this.data.cid;
    }
    get client() {
        return this._client;
    }
    get data() {
        return this._data;
    }
    get funds() {
        const api = this.client.contract;
        return api.funds(this.cid).then(e => {
            if (!e.ok)
                throw new Error(e.error);
            return e.data.funds;
        });
    }
    get opt() {
        return this._opt;
    }
    get is_stale() {
        const ival = this.opt.refresh_ival;
        return this._updated < now() - ival;
    }
    get status() {
        return this.data.status;
    }
    get updated_at() {
        return this._updated;
    }
    get vm() {
        return new ContractVM(this.client, this.data, this.opt);
    }
    async _digest() {
        const api = this.client.contract;
        const res = await api.digest(this.cid);
        if (!res.ok)
            throw new Error(res.error);
        const contract = { ...this._data, ...res.data.contract };
        validate_contract(contract);
        return contract;
    }
    async _fetch() {
        try {
            if (this.is_stale) {
                const res = await this._status();
                if (res.status !== this.status) {
                    const data = await this._digest();
                    this._update(data);
                }
                else {
                    this._updated = now();
                }
            }
            this.emit('fetch', this);
        }
        catch (err) {
            this.emit('error', err);
        }
        return this;
    }
    async _read() {
        const api = this.client.contract;
        const res = await api.read(this.cid);
        if (!res.ok)
            throw new Error(res.error);
        const contract = res.data.contract;
        validate_contract(contract);
        return contract;
    }
    async _status() {
        const api = this.client.contract;
        const res = await api.status(this.cid);
        if (!res.ok)
            throw new Error(res.error);
        return res.data.contract;
    }
    _update(data) {
        try {
            this._data = data;
            this._updated = now();
            this.emit('update', this);
        }
        catch (err) {
            this.emit('error', err);
        }
    }
    async cancel(signer) {
        const api = this.client.contract;
        const tkn = signer.request.contract_cancel(this.cid);
        const res = await api.cancel(this.cid, tkn);
        if (!res.ok)
            throw new Error(res.error);
        const ct = res.data.contract;
        this._update(ct);
        return this;
    }
    async fetch() {
        return this._fetch();
    }
    async poll(status, interval, retries) {
        for (let i = 0; i < retries; i++) {
            await this.fetch();
            if (this.status === status) {
                return this;
            }
            await sleep(interval * 1000);
        }
        throw new Error('polling timed out');
    }
    toJSON() {
        return this.data;
    }
    toString() {
        return JSON.stringify(this.data);
    }
}
