
import { __decorate, __param } from '../../../../../../../../external/tslib/tslib.es6.js';
import { $, append, reset } from '../../../../../base/browser/dom.js';
import { MarkdownString } from '../../../../../base/common/htmlContent.js';
import { DisposableStore } from '../../../../../base/common/lifecycle.js';
import '../../../../../base/common/observableInternal/index.js';
import { MouseTargetType } from '../../../../browser/editorBrowser.js';
import { EditorOption } from '../../../../common/config/editorOptions.js';
import { Range } from '../../../../common/core/range.js';
import { ILanguageService } from '../../../../common/languages/language.service.js';
import { HoverAnchorType, HoverForeignElementAnchor, RenderedHoverParts } from '../../../hover/browser/hoverTypes.js';
import { InlineCompletionsController } from '../controller/inlineCompletionsController.js';
import { InlineSuggestionHintsContentWidget } from './inlineCompletionsHintsWidget.js';
import { MarkdownRenderer } from '../../../../browser/widget/markdownRenderer/browser/markdownRenderer.js';
import { localize } from '../../../../../nls.js';
import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.service.js';
import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js';
import { IOpenerService } from '../../../../../platform/opener/common/opener.service.js';
import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.service.js';
import { GhostTextView } from '../view/ghostText/ghostTextView.js';
import { autorunWithStore, autorun } from '../../../../../base/common/observableInternal/autorun.js';
import { constObservable } from '../../../../../base/common/observableInternal/utils.js';

class InlineCompletionsHover {
    constructor(owner, range, controller) {
        this.owner = owner;
        this.range = range;
        this.controller = controller;
    }
    isValidForHoverAnchor(anchor) {
        return (anchor.type === HoverAnchorType.Range
            && this.range.startColumn <= anchor.range.startColumn
            && this.range.endColumn >= anchor.range.endColumn);
    }
}
let InlineCompletionsHoverParticipant = class InlineCompletionsHoverParticipant {
    constructor(_editor, _languageService, _openerService, accessibilityService, _instantiationService, _telemetryService) {
        this._editor = _editor;
        this._languageService = _languageService;
        this._openerService = _openerService;
        this.accessibilityService = accessibilityService;
        this._instantiationService = _instantiationService;
        this._telemetryService = _telemetryService;
        this.hoverOrdinal = 4;
    }
    suggestHoverAnchor(mouseEvent) {
        const controller = InlineCompletionsController.get(this._editor);
        if (!controller) {
            return null;
        }
        const target = mouseEvent.target;
        if (target.type === MouseTargetType.CONTENT_VIEW_ZONE) {
            const viewZoneData = target.detail;
            if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
                return ( new HoverForeignElementAnchor(
                    1000,
                    this,
                    Range.fromPositions(this._editor.getModel().validatePosition(viewZoneData.positionBefore || viewZoneData.position)),
                    mouseEvent.event.posx,
                    mouseEvent.event.posy,
                    false
                ));
            }
        }
        if (target.type === MouseTargetType.CONTENT_EMPTY) {
            if (controller.shouldShowHoverAt(target.range)) {
                return ( new HoverForeignElementAnchor(
                    1000,
                    this,
                    target.range,
                    mouseEvent.event.posx,
                    mouseEvent.event.posy,
                    false
                ));
            }
        }
        if (target.type === MouseTargetType.CONTENT_TEXT) {
            const mightBeForeignElement = target.detail.mightBeForeignElement;
            if (mightBeForeignElement && controller.shouldShowHoverAt(target.range)) {
                return ( new HoverForeignElementAnchor(
                    1000,
                    this,
                    target.range,
                    mouseEvent.event.posx,
                    mouseEvent.event.posy,
                    false
                ));
            }
        }
        if (target.type === MouseTargetType.CONTENT_WIDGET && target.element) {
            const ctx = GhostTextView.getWarningWidgetContext(target.element);
            if (ctx && controller.shouldShowHoverAt(ctx.range)) {
                return ( new HoverForeignElementAnchor(1000, this, ctx.range, mouseEvent.event.posx, mouseEvent.event.posy, false));
            }
        }
        return null;
    }
    computeSync(anchor, lineDecorations) {
        if (this._editor.getOption(EditorOption.inlineSuggest).showToolbar !== 'onHover') {
            return [];
        }
        const controller = InlineCompletionsController.get(this._editor);
        if (controller && controller.shouldShowHoverAt(anchor.range)) {
            return [( new InlineCompletionsHover(this, anchor.range, controller))];
        }
        return [];
    }
    renderHoverParts(context, hoverParts) {
        const disposables = ( new DisposableStore());
        const part = hoverParts[0];
        this._telemetryService.publicLog2('inlineCompletionHover.shown');
        if (this.accessibilityService.isScreenReaderOptimized() && !this._editor.getOption(EditorOption.screenReaderAnnounceInlineSuggestion)) {
            disposables.add(this.renderScreenReaderText(context, part));
        }
        const model = part.controller.model.get();
        const widgetNode = document.createElement('div');
        context.fragment.appendChild(widgetNode);
        disposables.add(autorunWithStore((reader, store) => {
            const w = store.add(this._instantiationService.createInstance(InlineSuggestionHintsContentWidget.hot.read(reader), this._editor, false, constObservable(null), model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.activeCommands, model.warning, () => {
                context.onContentsChanged();
            }));
            widgetNode.replaceChildren(w.getDomNode());
        }));
        model.triggerExplicitly();
        const renderedHoverPart = {
            hoverPart: part,
            hoverElement: widgetNode,
            dispose() { disposables.dispose(); }
        };
        return ( new RenderedHoverParts([renderedHoverPart]));
    }
    getAccessibleContent(hoverPart) {
        return localize(1264, 'There are inline completions here');
    }
    renderScreenReaderText(context, part) {
        const disposables = ( new DisposableStore());
        const $$1 = $;
        const markdownHoverElement = $$1('div.hover-row.markdown-hover');
        const hoverContentsElement = append(markdownHoverElement, $$1('div.hover-contents', { ['aria-live']: 'assertive' }));
        const renderer = ( new MarkdownRenderer({ editor: this._editor }, this._languageService, this._openerService));
        const render = (code) => {
            const inlineSuggestionAvailable = ( localize(1265, "Suggestion:"));
            const renderedContents = disposables.add(renderer.render(( new MarkdownString()).appendText(inlineSuggestionAvailable).appendCodeblock('text', code), {
                asyncRenderCallback: () => {
                    hoverContentsElement.className = 'hover-contents code-hover-contents';
                    context.onContentsChanged();
                }
            }));
            hoverContentsElement.replaceChildren(renderedContents.element);
        };
        disposables.add(autorun(reader => {
            const ghostText = part.controller.model.read(reader)?.primaryGhostText.read(reader);
            if (ghostText) {
                const lineText = this._editor.getModel().getLineContent(ghostText.lineNumber);
                render(ghostText.renderForScreenReader(lineText));
            }
            else {
                reset(hoverContentsElement);
            }
        }));
        context.fragment.appendChild(markdownHoverElement);
        return disposables;
    }
};
InlineCompletionsHoverParticipant = ( __decorate([
    ( __param(1, ILanguageService)),
    ( __param(2, IOpenerService)),
    ( __param(3, IAccessibilityService)),
    ( __param(4, IInstantiationService)),
    ( __param(5, ITelemetryService))
], InlineCompletionsHoverParticipant));

export { InlineCompletionsHover, InlineCompletionsHoverParticipant };
