"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkspaceProvider = void 0;
const vscode = __importStar(require("vscode"));
const https = __importStar(require("node:https"));
const http = __importStar(require("node:http"));
class WorkspaceProvider {
    constructor(storage, output) {
        this.storage = storage;
        this.output = output;
        this._onDidChangeTreeData = new vscode.EventEmitter();
        this.onDidChangeTreeData = this._onDidChangeTreeData.event;
        this.workspaces = [];
        this.refresh();
    }
    refresh() {
        this.fetchWorkspaces().then((items) => {
            this.workspaces = items;
            this._onDidChangeTreeData.fire();
        }, (err) => {
            this.output.appendLine(`Failed to fetch workspaces: ${err}`);
        });
    }
    getTreeItem(element) {
        const item = new vscode.TreeItem(`${element.owner}/${element.name}`);
        item.description = element.status;
        item.contextValue = 'workspace';
        item.command = {
            command: 'neuralinverse.cloud.open',
            title: 'Open Workspace',
        };
        return item;
    }
    getChildren() {
        return this.workspaces;
    }
    async fetchWorkspaces() {
        const deployment = this.storage.getDeployment();
        if (!deployment) {
            return [];
        }
        try {
            const data = await this.apiGet(deployment.url, deployment.token, '/api/v2/workspaces?q=owner:me');
            return (data.workspaces || []).map((w) => ({
                name: w.name,
                owner: w.owner_name,
                status: w.latest_build?.status || 'unknown',
            }));
        }
        catch {
            return [];
        }
    }
    apiGet(baseUrl, token, apiPath) {
        return new Promise((resolve, reject) => {
            const url = new URL(apiPath, baseUrl);
            const mod = url.protocol === 'https:' ? https : http;
            const req = mod.get(url, { headers: { 'Coder-Session-Token': token, Accept: 'application/json' } }, (res) => {
                const chunks = [];
                res.on('data', (c) => chunks.push(c));
                res.on('end', () => {
                    try {
                        resolve(JSON.parse(Buffer.concat(chunks).toString()));
                    }
                    catch (e) {
                        reject(e);
                    }
                });
            });
            req.on('error', reject);
        });
    }
}
exports.WorkspaceProvider = WorkspaceProvider;
//# sourceMappingURL=workspaceProvider.js.map