import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
import { CancellationTokenSource } from '../../../../base/common/cancellation.js';
import { Disposable, MutableDisposable } from '../../../../base/common/lifecycle.js';
import { observableValue } from '../../../../base/common/observableInternal/base.js';
import '../../../../base/common/observableInternal/derived.js';
import '../../../../base/common/observableInternal/autorun.js';
import '../../../../base/common/observableInternal/utils.js';
import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js';
import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js';
import { ITestResultService } from './testResultService.js';
import { TestingContextKeys } from './testingContextKeys.js';
import { IViewsService } from '../../../services/views/common/viewsService.js';
const ITestCoverageService = ( createDecorator('testCoverageService'));
let TestCoverageService = class TestCoverageService extends Disposable {
    constructor(contextKeyService, resultService, viewsService) {
        super();
        this.viewsService = viewsService;
        this.lastOpenCts = this._register(( new MutableDisposable()));
        this.selected = observableValue('testCoverage', undefined);
        this._isOpenKey = TestingContextKeys.isTestCoverageOpen.bindTo(contextKeyService);
        this._register(resultService.onResultsChanged(evt => {
            if ('completed' in evt) {
                const coverage = evt.completed.tasks.find(t => t.coverage.get());
                if (coverage) {
                    this.openCoverage(coverage, false);
                }
                else {
                    this.closeCoverage();
                }
            }
            else if ('removed' in evt && this.selected.get()) {
                const taskId = this.selected.get()?.fromTaskId;
                if (( evt.removed.some(e => ( e.tasks.some(t => t.id === taskId))))) {
                    this.closeCoverage();
                }
            }
        }));
    }
    async openCoverage(task, focus = true) {
        this.lastOpenCts.value?.cancel();
        const cts = this.lastOpenCts.value = ( new CancellationTokenSource());
        const coverage = task.coverage.get();
        if (!coverage) {
            return;
        }
        this.selected.set(coverage, undefined);
        this._isOpenKey.set(true);
        if (focus && !cts.token.isCancellationRequested) {
            this.viewsService.openView("workbench.view.testCoverage" , true);
        }
    }
    closeCoverage() {
        this._isOpenKey.set(false);
        this.selected.set(undefined, undefined);
    }
};
TestCoverageService = ( __decorate([
    ( __param(0, IContextKeyService)),
    ( __param(1, ITestResultService)),
    ( __param(2, IViewsService))
], TestCoverageService));
export { ITestCoverageService, TestCoverageService };
