/*
  Copyright (c) Microsoft Corporation.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
import { clsx } from '@web/uiUtils';
import { msToString } from '@isomorphic/formatUtils';
import * as React from 'react';
import './actionList.css';
import { stats, buildActionTree } from '@isomorphic/trace/traceModel';
import { asLocatorDescription } from '@isomorphic/locatorGenerators';
import { TreeView } from '@web/components/treeView';
import { ToolbarButton } from '@web/components/toolbarButton';
import { testStatusIcon } from './testUtils';
import { getMetainfo } from '@isomorphic/protocolMetainfo';
import { formatProtocolParam } from '@isomorphic/protocolFormatter';
const ActionTreeView = (TreeView);
export const ActionList = ({ actions, selectedAction, selectedTime, setSelectedTime, treeState, setTreeState, sdkLanguage, onSelected, onHighlighted, revealConsole, revealActionAttachment, isLive, actionFilterText, }) => {
    const { rootItem, itemMap } = React.useMemo(() => buildActionTree(actions), [actions]);
    const { selectedItem } = React.useMemo(() => {
        const selectedItem = selectedAction ? itemMap.get(selectedAction.callId) : undefined;
        return { selectedItem };
    }, [itemMap, selectedAction]);
    const isError = React.useCallback((item) => {
        return !!item.action.error?.message;
    }, []);
    const onAccepted = React.useCallback((item) => {
        return setSelectedTime({ minimum: item.action.startTime, maximum: item.action.endTime });
    }, [setSelectedTime]);
    const render = React.useCallback((item) => {
        const showAttachments = !!revealActionAttachment && !!item.action.attachments?.length;
        return renderAction(item.action, { sdkLanguage, revealConsole, revealActionAttachment: () => revealActionAttachment?.(item.action.callId), isLive, showDuration: true, showBadges: true, showAttachments });
    }, [isLive, revealConsole, revealActionAttachment, sdkLanguage]);
    const isVisible = React.useCallback((item) => {
        const timeVisible = !selectedTime || !item.action || (item.action.startTime <= selectedTime.maximum && item.action.endTime >= selectedTime.minimum);
        if (!timeVisible)
            return false;
        const title = renderTitleForCall(item.action).title;
        if (!actionFilterText)
            return true;
        const isIncluded = title.toLowerCase().includes(actionFilterText.toLowerCase());
        return isIncluded ? true : 'if-needed';
    }, [selectedTime, actionFilterText]);
    const onSelectedAction = React.useCallback((item) => {
        onSelected?.(item.action);
    }, [onSelected]);
    const onHighlightedAction = React.useCallback((item) => {
        onHighlighted?.(item?.action);
    }, [onHighlighted]);
    return <div className='vbox action-list-container'>
    {selectedTime && <div className='action-list-show-all' onClick={() => setSelectedTime(undefined)}><span className='codicon codicon-triangle-left'></span>Show all</div>}
    <ActionTreeView name='actions' rootItem={rootItem} treeState={treeState} setTreeState={setTreeState} selectedItem={selectedItem} onSelected={onSelectedAction} onHighlighted={onHighlightedAction} onAccepted={onAccepted} isError={isError} isVisible={isVisible} render={render} autoExpandDepth={actionFilterText?.trim() ? 5 : 0}/>
  </div>;
};
export const renderAction = (action, options) => {
    const { sdkLanguage, revealConsole, revealActionAttachment, isLive, showDuration, showBadges, showAttachments } = options;
    const { errors, warnings } = stats(action);
    const locator = action.params.selector ? asLocatorDescription(sdkLanguage || 'javascript', action.params.selector) : undefined;
    const isSkipped = action.class === 'Test' && action.method === 'test.step' && action.annotations?.some(a => a.type === 'skip');
    let time = '';
    if (action.endTime)
        time = msToString(action.endTime - action.startTime);
    else if (action.error)
        time = 'Timed out';
    else if (!isLive)
        time = '-';
    const { elements, title } = renderTitleForCall(action);
    return <div className='action-title vbox'>
    <div className='hbox'>
      <span className='action-title-method' title={title}>{elements}</span>
      {(showDuration || showBadges || showAttachments || isSkipped) && <div className='spacer'></div>}
      {showAttachments && <ToolbarButton icon='attach' title='Open Attachment' onClick={() => revealActionAttachment?.()}/>}
      {showDuration && !isSkipped && <div className='action-duration'>{time || <span className='codicon codicon-loading'></span>}</div>}
      {isSkipped && <span className={clsx('action-skipped', 'codicon', testStatusIcon('skipped'))} title='skipped'></span>}
      {showBadges && <div className='action-icons' onClick={() => revealConsole?.()}>
        {!!errors && <div className='action-icon'><span className='codicon codicon-error'></span><span className='action-icon-value'>{errors}</span></div>}
        {!!warnings && <div className='action-icon'><span className='codicon codicon-warning'></span><span className='action-icon-value'>{warnings}</span></div>}
      </div>}
    </div>
    {locator && <div className='action-title-selector' title={locator}>{locator}</div>}
  </div>;
};
export function renderTitleForCall(action, sdkLanguage) {
    let titleFormat = action.title ?? getMetainfo({ type: action.class, method: action.method })?.title ?? action.method;
    titleFormat = titleFormat.replace(/\n/g, ' ');
    const elements = [];
    const title = [];
    let currentIndex = 0;
    const regex = /\{([^}]+)\}/g;
    let match;
    while ((match = regex.exec(titleFormat)) !== null) {
        const [fullMatch, quotedText] = match;
        const chunk = titleFormat.slice(currentIndex, match.index);
        elements.push(chunk);
        title.push(chunk);
        const param = formatProtocolParam(action.params, quotedText);
        if (param === undefined) {
            elements.push(fullMatch);
            title.push(fullMatch);
        }
        else if (match.index === 0) {
            elements.push(param);
            title.push(param);
        }
        else {
            elements.push(<span key={elements.length} className='action-title-param'>{param}</span>);
            title.push(param);
        }
        currentIndex = match.index + fullMatch.length;
    }
    if (currentIndex < titleFormat.length) {
        const chunk = titleFormat.slice(currentIndex);
        elements.push(chunk);
        title.push(chunk);
    }
    const locator = action.params.selector ? asLocatorDescription(sdkLanguage || 'javascript', action.params.selector) : undefined;
    if (locator) {
        title.push(' ');
        title.push(locator);
    }
    return { elements, title: title.join('') };
}
//# sourceMappingURL=actionList.js.map