import { __decorate, __metadata } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { Component, useState } from "react";
import { format } from "date-fns";
import { TabContext, TabList, TabPanel } from "@material-ui/lab";
import { Collapse, Tab } from "@material-ui/core";
import styled from "styled-components";
import { StyledButton } from "../Components/Button";
import { ResetIcon } from "../Icon/ResetIcon";
import { RunIcon } from "../Icon/RunIcon";
import { BaseTestResultData, TestResultData } from "../../Common/Testing/TestResultData";
import { TestContext } from "../../Tester/TestContext";
import { XExecutionData } from "../../Common/Data/ExecutionData/XExecutionData";
import { AutoBind } from "../../Common/AutoBind";
import { ObjectDataDefinition } from "../../Common/Data/Definitions/ObjectDataDefinition";
import { XValueEditor } from "../DataEditing";
import { OpenBlueIcon } from "../Icon/OpenBlueIcon";
import { DropdownBlueIcon } from "../Icon/DropdownBlueIcon";
import { EventLogType } from "../../Common/Event/EventLog";
function getNormalizedTitle(title) {
    return (title || "").replace(/_/g, " ");
}
export class XExecutableTester extends Component {
    constructor(props) {
        super(props);
        this.state = {
            testcontext: new TestResultData(),
            value: undefined,
            data: new XExecutionData(),
            running: false,
            currentView: "ui",
        };
    }
    onStart(newdata) {
        this.setState({
            running: false,
            data: newdata,
        });
        try {
            this.props.executable.run(newdata, this.state.testcontext);
        }
        catch (_a) { }
        let newState = {
            running: true,
            value: this.state.value,
        };
        if (this.state.testcontext.items.length > 0) {
            newState["value"] = this.state.testcontext.items[this.state.testcontext.items.length - 1];
        }
        this.setState(newState);
    }
    onReset(event) {
        event.stopPropagation();
        this.setState({
            testcontext: new TestResultData(),
            value: undefined,
        });
    }
    renderTree() {
        return (_jsxs(TesterTreeView, { children: [_jsx(TesterStatus, { children: this.state.testcontext.items.length
                        ? `Debugging`
                        : `Welcome to the debugging system. Enter first data and push on "Play" to starting testing` }, void 0),
                this.state.testcontext.items
                    .sort((a, b) => {
                    if (a.when > b.when)
                        return -1;
                    return 1;
                })
                    .map((item, idx) => (_jsx(TesterTreeItem, { item: item, onSelect: (selecteditem) => this.setState({ value: selecteditem }) }, `${idx}-${item.when.getTime()}`)))] }, void 0));
    }
    onChangeView(_event, value) {
        this.setState({
            currentView: value,
        });
    }
    render() {
        // render side tree
        // render run button
        // render ui for parameters to be gathered
        // when its run, find the first node with a ui and render the ui to the right
        var _a, _b, _c;
        const objdef = new ObjectDataDefinition();
        objdef.fields = this.props.executable.getInputDefinition().fields;
        let tabs = [
            { name: "UI", ui: (_b = (_a = this.state.value) === null || _a === void 0 ? void 0 : _a.render()) !== null && _b !== void 0 ? _b : _jsx(_Fragment, {}, void 0) },
            {
                name: "Events",
                ui: (_jsx(EventsRender, { children: (((_c = this.state.value) === null || _c === void 0 ? void 0 : _c.logs) || []).map((log) => (_jsxs(EventRender, Object.assign({ type: log.type }, { children: [format(log.when, "dd.MM.yy HH:mm:ss.sss"), ": ", log.message] }), log.when.getTime()))) }, void 0)),
            },
        ];
        if (this.state.value && this.state.value.getTabs) {
            tabs = this.state.value.getTabs();
        }
        return (_jsx(TestContext.Provider, Object.assign({ value: this.state.value }, { children: _jsx(TabContext, Object.assign({ value: this.state.currentView }, { children: _jsxs(Render, { children: [_jsxs(TesterHeader, { children: [_jsxs(TesterControls, { children: [_jsx("div", { children: "Debugging" }, void 0),
                                        _jsxs(TestActions, { children: [_jsx(StyledButton, Object.assign({ endIcon: _jsx(ResetIcon, {}, void 0), size: "small", onClick: this.onReset }, { children: "Reset" }), void 0),
                                                _jsxs(RunButton, Object.assign({ "data-testid": "XExecutableTester-play", onClick: objdef.fields.length > 0
                                                        ? undefined
                                                        : () => this.onStart(new XExecutionData()) }, { children: [objdef.fields.length > 0 && (_jsx(XValueEditor, { forData: objdef, value: this.state.data, onUpdate: (newValue) => {
                                                                this.onStart(newValue);
                                                            }, mode: "edit_mode", editMode: "layer" }, void 0)), "Play", _jsx(RunIcon, {}, void 0)] }), void 0)] }, void 0)] }, void 0),
                                _jsx(TabList, Object.assign({ onChange: this.onChangeView, color: "primary" }, { children: tabs.map((tab) => (_jsx(Tab, { value: tab.name, label: tab.name }, tab.name))) }), void 0)] }, void 0),
                        _jsxs(TesterRender, { children: [this.renderTree(), _jsx(BuilderRender, { children: tabs.map((tab) => (_jsx(TabPanel, Object.assign({ value: tab.name }, { children: tab.ui }), tab.name))) }, void 0)] }, void 0)] }, void 0) }), void 0) }), void 0));
    }
}
__decorate([
    AutoBind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [XExecutionData]),
    __metadata("design:returntype", void 0)
], XExecutableTester.prototype, "onStart", null);
__decorate([
    AutoBind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], XExecutableTester.prototype, "onReset", null);
__decorate([
    AutoBind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], XExecutableTester.prototype, "renderTree", null);
__decorate([
    AutoBind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], XExecutableTester.prototype, "onChangeView", null);
const TesterTreeItem = (props) => {
    const [iscollapsed, setIsCollapsed] = useState(true);
    const isclickable = !!props.item.render();
    const subitems = props.item.items;
    const haschildren = !!subitems.find((item) => item instanceof BaseTestResultData);
    const onSelect = (item) => {
        props.onSelect(item);
    };
    const onToggle = (event) => {
        event.stopPropagation();
        if (haschildren) {
            setIsCollapsed(!iscollapsed);
        }
    };
    return (_jsxs(TesterSection, Object.assign({ "data-testid": `treeitem-${props.item.type}`, onClick: (event) => {
            event.stopPropagation();
            if (isclickable) {
                onSelect(props.item);
            }
            else if (subitems.length > 0) {
                let firstitem = subitems.find((it) => it instanceof BaseTestResultData);
                if (firstitem) {
                    onSelect(firstitem);
                }
                setIsCollapsed(false);
            }
        } }, { children: [_jsxs(TesterSectionHeader, { children: [_jsx(ExpandIconButton, Object.assign({ visible: haschildren, onClick: onToggle }, { children: iscollapsed ? _jsx(OpenBlueIcon, {}, void 0) : _jsx(DropdownBlueIcon, {}, void 0) }), void 0),
                    _jsxs(TesterStartTime, { children: [getNormalizedTitle(props.item.type), " (", props.item.getDuration(), ")", props.item.isShowResult && (_jsxs(_Fragment, { children: [_jsx("br", {}, void 0), "Result: ", props.item.result] }, void 0))] }, void 0)] }, void 0),
            haschildren && (_jsx(Collapse, Object.assign({ in: !iscollapsed }, { children: _jsx(TesterSectionBody, { children: subitems.map((subi) => {
                        if (subi instanceof BaseTestResultData) {
                            return (_jsx(TesterTreeItem, { item: subi, onSelect: props.onSelect }, subi.when.getTime()));
                        }
                        return _jsx(React.Fragment, {}, subi.when.getTime());
                    }) }, void 0) }), void 0))] }), void 0));
};
const TesterSectionHeader = styled.div `
    display: flex;
    flex-direction: row;
    padding: 4px 8px;
`;
const TesterSectionBody = styled.div `
    padding-left: 8px;
`;
const ExpandIconButton = styled.div `
    width: 16px;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    visibility: ${(props) => (props.visible ? "visible" : "hidden")};
`;
const TesterRender = styled.div `
    position: relative;
    display: flex;
    flex-direction: row;
    height: 100%;

    background: #fff;
`;
const TesterHeader = styled.div `
    position: relative;
    display: flex;
    flex-direction: row;
`;
const TesterTreeView = styled.div `
    display: flex;
    flex-direction: column;
    width: 375px;

    border: 1px solid rgba(39, 41, 50, 0.2);

    background: #fcfcfe;

    box-sizing: border-box;
    border-radius: 4px;

    padding: 8px 12px;
`;
const BuilderRender = styled.div `
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
`;
const TesterControls = styled.div `
    padding: 8px 20px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    font-family: Inter;
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: 16px;
    letter-spacing: 0em;
    text-align: left;

    color: #272932;

    width: 375px;
`;
const TestActions = styled.div `
    display: flex;
    flex-direction: row;
`;
const TesterStatus = styled.div `
    padding: 4px 8px;

    font-family: Inter;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: 17px;
    letter-spacing: 0px;
    text-align: left;
    color: #606881;
`;
const TesterStartTime = styled.div `
    font-family: Inter;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: 17px;
    letter-spacing: 0px;
    text-align: left;
    color: #606881;
`;
const TesterSection = styled.div `
    cursor: pointer;
`;
const EventsRender = styled.div `
    display: flex;
    flex-direction: column;
`;
const EventRender = styled.div `
    color: ${(props) => (props.type === EventLogType.ERROR ? "#EE3E54" : "rgb(39, 41, 50)")};
`;
const RunButton = styled.div `
    display: flex;
    align-items: center;

    font-style: normal;
    font-weight: 500;
    font-size: 12px;
    line-height: 18px;
    color: #272932;
    font-family: Inter;

    padding: 6px 12px;
    position: relative;

    cursor: pointer;

    &:hover {
        background-color: rgba(0, 0, 0, 0.04);
    }

    & > img {
        margin-right: -2px;
        margin-left: 8px;
    }

    .ValueEditor-root {
        position: absolute;
        left: 0;
        right: 0;
        opacity: 0;
        top: 0;
        bottom: 0;
    }
`;
const Render = styled.div `
    display: flex;
    width: 100%;
    height: 100%;
    flex-direction: column;
`;
//# sourceMappingURL=XExecutableTester.js.map