import ky from 'ky';
import { snooze } from './snooze.js';
function cacheBust(url) {
    const ts = Date.now();
    const sep = url.indexOf('?') < 0 ? '?' : '&';
    return `${url}${sep}cb=${ts}`;
}
export class Gitea {
    _protocol;
    _domain;
    _apiPrefix;
    _token;
    constructor(options = {}) {
        this._protocol = options.protocol || 'https';
        this._domain = options.domain || 'gitea.artixlinux.org';
        this._apiPrefix = options.apiPrefix || '/api/v1';
        this._token = options.token || '';
    }
    setToken(token) {
        if (token) {
            this._token = token;
        }
    }
    getHomepage() {
        return `${this._protocol}://${this._domain}/`;
    }
    getUrlPrefix() {
        return `${this._protocol}://${this._domain}${this._apiPrefix}`;
    }
    async getRepo(...args) {
        try {
            const headers = {};
            if (this._token) {
                headers['Authorization'] = `token ${this._token}`;
            }
            const resp = await ky.get(cacheBust(`${this.getUrlPrefix()}/repos/${args.join('/')}`), {
                headers
            });
            return await resp.json();
        }
        catch (err) {
            throw err;
        }
    }
    async getCommits(...args) {
        try {
            const headers = {};
            if (this._token) {
                headers['Authorization'] = `token ${this._token}`;
            }
            const resp = await ky.get(cacheBust(`${this.getUrlPrefix()}/repos/${args.join('/')}/commits?limit=10`), {
                headers
            });
            return await resp.json();
        }
        catch (err) {
            throw err;
        }
    }
    async getStatus(...args) {
        try {
            const commits = await this.getCommits(...args);
            const headers = {};
            if (this._token) {
                headers['Authorization'] = `token ${this._token}`;
            }
            const resp = await ky.get(cacheBust(`${this.getUrlPrefix()}/repos/${args.join('/')}/commits/${commits[0]?.sha}/status`), {
                headers
            });
            return await resp.json();
        }
        catch (err) {
            throw err;
        }
    }
    async getTags(...args) {
        try {
            const headers = {};
            if (this._token) {
                headers['Authorization'] = `token ${this._token}`;
            }
            const resp = await ky.get(cacheBust(`${this.getUrlPrefix()}/repos/${args.join('/')}/tags`), {
                headers
            });
            return await resp.json();
        }
        catch (err) {
            throw err;
        }
    }
    async getHooks(...args) {
        try {
            const headers = {};
            if (this._token) {
                headers['Authorization'] = `token ${this._token}`;
            }
            const resp = await ky.get(cacheBust(`${this.getUrlPrefix()}/repos/${args.join('/')}/hooks`), {
                headers
            });
            return await resp.json();
        }
        catch (err) {
            throw err;
        }
    }
    async sendTestWebhook(...args) {
        try {
            const headers = {};
            if (this._token) {
                headers['Authorization'] = `token ${this._token}`;
            }
            const hook = (await this.getHooks(...args)).find(hook => hook.active === true);
            if (!hook) {
                throw new Error('No active webhook found');
            }
            await ky.post(`${this.getUrlPrefix()}/repos/${args.join('/')}/hooks/${hook.id}/tests`, {
                headers
            });
        }
        catch (err) {
            throw err;
        }
    }
    async waitForBuild(lastHash, ...args) {
        let missingStatusCount = 0;
        while (true) {
            let status;
            try {
                status = await this.getStatus(...args);
            }
            catch {
                status = null;
            }
            if (!status) {
                await snooze(30000);
                continue;
            }
            if (!status.sha && !status.state) {
                if (++missingStatusCount > 3) {
                    console.log('No build info detected. Sending test webhook...');
                    missingStatusCount = 0;
                    await this.sendTestWebhook(...args);
                }
                await snooze(30000);
            }
            else if (status.sha !== lastHash) {
                if (status.state === 'success') {
                    break;
                }
                else if (status.state === 'failure') {
                    throw new Error(`Build ${status.sha} failed.`);
                }
            }
            await snooze(5000);
        }
    }
}
export default Gitea;
//# sourceMappingURL=gitea.js.map