import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import classNames from '../../../../_virtual/index.js';
import { checkEmpty } from '../../../../utils/checkEmpty/checkEmpty.js';
import { ffid } from '../../../../utils/ffID/ffid.js';
import MachineInputField from '../../../MachineInputField/MachineInputField.js';
import Icon from '../../../Icon/Icon.js';
import Typography from '../../../Typography/Typography.js';
import Button from '../../../Button/Button.js';
import Tooltip from '../../../Tooltip/Tooltip.js';
import DataSetTooltip from '../DatasetTooltip/DataSetTooltip.js';
import { isEmptyObject } from '../../../../utils/isEmptyObject/isEmptyObject.js';
import { useEnvironmentalVariableMaps } from '../../context/EnvironmentVariableMapsContext.js';

const Branches = ({ machineInstances, rowIndex, machineColumnCount, nextRowMachineInstance, previousRowMachineInstance, onAddBrowser, onDeleteBrowser, onAddRunBrowser, onUpdateDataSetList, onUpdateAddBrowserInstance, addInstanceLabel = '', scriptType = '', projectType = '', readOnly, maxRunCount, }) => {
    const evenRow = rowIndex % 2 === 0;
    const lastMachineInstance = checkEmpty(machineInstances[machineColumnCount - 1]);
    const environmentalMaps = useEnvironmentalVariableMaps();
    const { testDataSetMap = {}, globalVariableMap = {}, projectVariableMap = {}, } = environmentalMaps || {};
    const showLEndArrow = () => readOnly
        ? !lastMachineInstance && !checkEmpty(nextRowMachineInstance)
        : !lastMachineInstance;
    const getBorderStyle = (currentBranch, nextBranch) => {
        if (currentBranch &&
            nextBranch &&
            'machineInstanceId' in currentBranch &&
            'machineInstanceId' in nextBranch) {
            return currentBranch.machineInstanceId === nextBranch.machineInstanceId
                ? 'dashed'
                : 'solid';
        }
        return 'solid';
    };
    const showMiddleArrow = (index) => machineInstances?.length - 1 !== index && machineColumnCount > 1;
    const getGridTemplateColumnStyle = () => {
        if (machineColumnCount === 1) {
            return `24px minmax(min-content, auto) 24px`;
        }
        return `24px minmax(min-content, auto) repeat(${machineColumnCount - 1}, 40px minmax(min-content, auto)) 24px`;
    };
    const getMachineLabelOptionList = (type = '', machineInstance) => {
        const { executionEnv, browserName, browserVersion, machineInfo: { osVersion, iconName, osName, hostName }, deviceInfo, fireCloudProjectName = '', } = machineInstance;
        const getEnvironment = (environment = '') => {
            if (environment?.toLowerCase() === 'local')
                return 'local';
            if (environment?.toLowerCase()?.includes('browserstack'))
                return 'Browserstack';
            if (environment?.toLowerCase()?.includes('lambdatest'))
                return 'LambdaTest';
            if (environment?.toLowerCase()?.includes('saucelabs'))
                return 'SauceLabs';
            if (environment?.toLowerCase()?.includes('fireflink device farm'))
                return 'fireflink';
            return '';
        };
        // Base options
        const baseOptions = [
            {
                label: executionEnv === 'FireFlink Device Farm'
                    ? fireCloudProjectName
                    : executionEnv,
                type: getEnvironment(executionEnv),
            },
        ];
        if (scriptType?.toLowerCase() === 'manual') {
            baseOptions.push({
                label: hostName || '',
                type: executionEnv?.toLowerCase() === 'local' ? 'local' : '',
            });
        }
        // Web-specific options
        const webOptions = [
            {
                label: osVersion || '',
                type: iconName || osName,
            },
            {
                label: browserVersion,
                type: browserName,
            },
        ];
        // Mobile-specific options
        const mobileOptions = deviceInfo?.reduce((acc, device) => {
            if (device) {
                acc?.push({
                    label: device?.name,
                    type: scriptType?.toLowerCase() === 'manual'
                        ? 'android'
                        : device?.platform,
                    version: scriptType?.toLowerCase() === 'manual' ? device?.version : '',
                });
            }
            return acc;
        }, []);
        // Determine options based on the type
        switch (type.toLowerCase()) {
            case 'web':
            case 'web service':
                return [...baseOptions, ...webOptions];
            case 'web & mobile':
            case 'ms dynamics':
            case 'salesforce':
                return [...baseOptions, ...webOptions, ...mobileOptions];
            case 'mobile':
                return [...baseOptions, ...mobileOptions];
            default:
                return [];
        }
    };
    const hideDataSet = scriptType?.toLowerCase() !== 'manual';
    // checkEmpty is not suitable for this case
    const showEndDot = (machineInstances) => {
        return checkEmpty(machineInstances)
            ? isEmptyObject(machineInstances) || nextRowMachineInstance !== undefined
            : true;
    };
    return (jsxs("div", { className: classNames({
            'ff-connecting-branch-grid': evenRow,
            'ff-connecting-branch-grid-reverse': !evenRow,
        }), style: {
            gridTemplateColumns: getGridTemplateColumnStyle(),
        }, children: [jsxs("div", { className: "ff-connecting-branch-start-wrapper", children: [jsx("div", { className: classNames({
                            'ff-connecting-branch-arrow': evenRow,
                            'ff-connecting-branch-arrow-reverse': !evenRow,
                        }) }), jsx("div", { className: classNames({
                            'ff-connecting-branch-container': evenRow,
                            'ff-connecting-branch-container-reverse': !evenRow,
                        }), style: {
                            border: `1px ${getBorderStyle(machineInstances[0], previousRowMachineInstance)} var(--ff-connecting-branch-color)`,
                            borderTop: 'none',
                            borderLeft: `${!evenRow && 'none'}`,
                            borderRight: `${evenRow && 'none'}`,
                        } })] }), machineInstances?.map((machineInstance, index) => {
                // const options = getMachineLabelOptionList(
                //   projectType,
                //   machineInstance
                // ) as MachineType[];
                // const isMissing = options?.some((opt) => checkEmpty(opt?.label));
                const { runCount = 'runCount' in machineInstance
                    ? machineInstance.runCount
                    : 0, numberOfRuns = 0, machineInstanceId = '', peVariableSetId = '', globalVariableSetId = '', testDataSetId = '', testDataSetName = '', peVariableSetName = '', globalVariableSetName = '', } = machineInstance;
                return (jsxs(Fragment, { children: [!checkEmpty(machineInstance) ? (jsxs("div", { children: [jsxs("div", { className: "ff-connecting-branch-input-point-wrapper", children: [showEndDot(machineInstances[index + 1]) && (jsx("div", { className: classNames({
                                                'ff-connecting-branch-point': evenRow,
                                                'ff-connecting-branch-point-reverse': !evenRow,
                                            }) })), jsx(MachineInputField, { runCount: runCount, options: getMachineLabelOptionList(projectType, machineInstance), contentReverse: !evenRow, modalId: `${machineInstanceId}-runCount-${runCount - 1}`, onClick: () => runCount == 1 || scriptType !== 'Automation'
                                                ? onUpdateAddBrowserInstance(`${machineInstanceId}-runCount-0`, machineInstance)
                                                : null, scriptType: scriptType, readOnly: readOnly }, ffid())] }), jsxs("div", { className: classNames({
                                        'ff-connecting-branch-datalist': evenRow,
                                        'ff-connecting-branch-datalist-reverse': !evenRow,
                                    }), children: [hideDataSet && (jsxs(Fragment, { children: [jsx("div", { id: `ff-sequential-branch-dataset-${machineInstanceId}-${runCount}`, className: "ff-dataset-list-branch", onClick: () => {
                                                        if (readOnly)
                                                            return;
                                                        onUpdateDataSetList(`ff-sequential-branch-dataset-${machineInstanceId}-${runCount}`, {
                                                            peVariableSetId: peVariableSetId,
                                                            globalVariableSetId: globalVariableSetId,
                                                            testDataSetId: testDataSetId,
                                                            testDataSetName: testDataSetName,
                                                            globalVariableSetName: globalVariableSetName,
                                                            peVariableSetName: peVariableSetName,
                                                        }, true, numberOfRuns, machineInstanceId);
                                                    }, children: jsxs(Tooltip, { placement: "bottom", title: jsx(Fragment, { children: jsx(DataSetTooltip, { datSetToolTip: {
                                                                    peVariableSetName: projectVariableMap[peVariableSetId] || '',
                                                                    globalVariableSetName: globalVariableMap[globalVariableSetId] ||
                                                                        '',
                                                                    testDataSetName: testDataSetMap[testDataSetId] || '',
                                                                } }) }), style: { display: 'flex', alignItems: 'center' }, children: [jsx(Icon, { name: "datalist_icon", className: "ff-connecting-icon", hoverEffect: true }), jsx(Typography, { className: "ff-connecting-text", color: "var(--ff-connecting-branch-color)", children: "Data Set List" })] }) }), !readOnly && (jsx(Fragment, { children: jsx(Tooltip, { placement: "bottom", title: numberOfRuns >= maxRunCount
                                                            ? `Maximum ${maxRunCount} runs are allowed.`
                                                            : '', children: jsxs("div", { className: "ff-environment-run-container", onClick: numberOfRuns >= maxRunCount
                                                                ? undefined
                                                                : () => onAddRunBrowser(machineInstanceId), children: [jsx(Icon, { name: "plus_icon", className: "ff-connecting-run-icon", color: "var(--ff-connecting-branch-color)", hoverEffect: true, disabled: numberOfRuns >= maxRunCount ? true : false }), jsx(Typography, { className: "ff-connecting-run-text", color: "var(--ff-connecting-branch-color)", style: {
                                                                        opacity: numberOfRuns >= maxRunCount ? 0.5 : 1,
                                                                    }, children: "Run" })] }) }) }))] })), !readOnly && (jsx(Tooltip, { title: "Delete", children: jsx(Icon, { name: "delete", className: "ff-connecting-delete-icon", onClick: () => onDeleteBrowser(machineInstanceId, runCount), color: "var(--ff-connecting-branch-delete-color)", hoverEffect: true }) }))] })] })) : (!readOnly && (jsx("div", { className: "ff-connecting-branch-browser-button", children: jsx(Button, { id: `ff-sequential-branch-add-${machineInstanceId}`, variant: "tertiary", label: addInstanceLabel, iconName: 'plus_icon', iconPosition: !evenRow ? 'right' : 'left', onClick: () => {
                                    if (readOnly)
                                        return;
                                    onAddBrowser(`ff-sequential-branch-add-${machineInstanceId}`);
                                } }) }))), showMiddleArrow(index) && (jsx("div", { className: "ff-connecting-branch-middle-arrow", style: {
                                borderTop: `1px ${getBorderStyle(machineInstance, machineInstances[index + 1])} var(--ff-connecting-branch-color)`,
                            }, children: jsx("div", { className: classNames({
                                    'ff-connecting-branch-arrow': evenRow,
                                    'ff-connecting-branch-arrow-reverse': !evenRow,
                                }) }) }))] }, ffid()));
            }), showLEndArrow() && (jsx("div", { className: classNames({
                    'ff-connecting-branch-end-arrow': evenRow,
                    'ff-connecting-branch-end-arrow-reverse': !evenRow,
                }), style: {
                    border: `1px ${getBorderStyle(machineInstances[machineColumnCount - 1], nextRowMachineInstance)} var(--ff-connecting-branch-color)`,
                    borderBottom: 'none',
                    borderLeft: `${evenRow && 'none'}`,
                    borderRight: `${!evenRow && 'none'}`,
                } }))] }));
};

export { Branches as default };
//# sourceMappingURL=Branches.js.map
