<!DOCTYPE html>
<html lang="en">

<head>
    <% include ../partials/head %>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/loader.min.js"></script>
    <script src="/static/monaco.js"></script>
</head>

<body>
    <% include ../partials/nav %>
    <div class="container">
        <div class="jumbotron">
            <h1 class="display-4">AIFEX </h1>
            <p class="lead">Improve the quality, efficiency and diversity of your exploratory test sessions</p>
            <hr class="my-4"></hr>
            <h1>Update a WebSite <a href="/documentation-website" target="_blank"><i class="fas fa-question-circle"></i></a></h1>
            <% if (successMessage) { %>
                <div class="alert alert-success" role="alert">
                    <h4>Success</h4>
                    <p><%= successMessage %> : <a role="button" class="btn btn-success" href="/dashboard/session/start?webSiteId=<%=webSite.id%>&webSiteName=<%=webSite.name%>">Start Session</a></p>
                    <hr>
                    Or go back to : <a role="button" class="btn btn-primary" href="/"> Home</a>
                    <a role="button" class="btn btn-primary" href="/account/account">Dashboard</a>
                    
                </div>
            <% } %>
            <% if (errorMessage) { %>
            <div class="alert alert-danger" role="alert">
                Error : <%= errorMessage %>
            </div>
            <% } %>
            <form onsubmit="return validation(event)" action="/dashboard/website/update" method="post" encType="multipart/form-data" id="form-container">
                <input id="id" name="id" value="<%= webSite.id%>" hidden></input>
                <div class="form-group row">
                    <label for="name" class="col-sm-2 col-form-label">Name</label>
                    <div class="col-sm-4">
                        <input type="text" class="form-control" name="name" id="name" value="<%= webSite.name %>">
                    </div>
                </div>

                <div class="form-group row">
                    <label for="websiteURL" class="col-sm-2 col-form-label">URL</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="url" id="url"
                            value="<%= webSite.url %>">
                    </div>
                </div>
                <div class="form-group row">
                    <label for="mappingList" class="col-sm-2 col-form-label">mappingList</label>
                    <div class="col-sm-10" style="resize: vertical;overflow: auto;height:400px;border:1px solid grey"
                        id="monaco" htmlFormId="form-container" formFieldName="mappingList" >
                        <div id="monaco-code" style="display: none;"><% if (Array.isArray(webSite.mappingList)) { %><%-
                            JSON.stringify(webSite.mappingList.map(rule => {
                                return {
                                    match: rule.match,
                                    output:rule.output,
                                    context:rule.context
                                };
                            }), undefined, 4) %>
                        <% } else { %>
                            <%- webSite.mappingList %>
                        <% } %>
                        </div>
                    </div>
                </div>
                <!--
                <h3>Steps</h2>
                    <input id="stepList" name="stepList" type="hidden">
                    <button id="addStepButton" class="btn btn-primary" type="button">Add Step</button>
                    <div id="step_group"></div>
                -->
                <button type="submit" class="btn btn-primary">Update</button>
            </form>
        </div>
    </div>

    <script>
        document.getElementById("monaco-code").addEventListener("change", (e) => updateActionList(e.value))
        let stepLength = 0;
        let actionList = [];
        document.getElementById("addStepButton").addEventListener("click", () => addStep());
        const code = document.getElementById("monaco-code").textContent;
        updateActionList(code);

        let name;
        let expression;

        <% if (stepList) { %>
            <% stepList.forEach((step) => { %>
                    console.log(<%- step.expression %>)
                    name = "<%- step.name %>";
                    expression = "<%- step.expression %>";
                    addStep(name, expression);
            <% }) %>
        <% } %>
        


        function addStep(name, expression) {
            stepLength++;
            const stepGroup = document.getElementById("step_group");
            const stepDiv = document.createElement("div");

            stepDiv.classList.add("form-group");
            stepGroup.appendChild(stepDiv);

            const stepTitle = document.createElement("h5");
            stepTitle.textContent = `Step ${stepLength}`
            stepDiv.appendChild(stepTitle);

            const stepLabelName = document.createElement("label");
            stepLabelName.classList.add(["col-sm-2", "col-form-label"]);
            stepLabelName.textContent = `name`
            stepDiv.appendChild(stepLabelName);
            
            const stepNameInput = document.createElement("input");
            stepNameInput.setAttribute("required", true);
            stepNameInput.setAttribute("stepName", stepLength)
            stepNameInput.setAttribute("type", "text");
            stepNameInput.classList.add("form-control");
            if (name) {
                stepNameInput.value = name;
            }
            stepDiv.appendChild(stepNameInput);

            const stepLabelContent = document.createElement("label");
            stepLabelContent.classList.add(["col-sm-2", "col-form-label"]);
            stepLabelContent.textContent = `Content`
            stepDiv.appendChild(stepLabelContent);

            const selectActionGroup = document.createElement("div");
            selectActionGroup.classList.add("input-group");
            const selectPrependGroup = document.createElement("div");
            selectActionGroup.appendChild(selectPrependGroup)
            selectPrependGroup.classList.add("input-group-prepend");
            const spanAddAction = document.createElement("span");
            spanAddAction.classList.add("input-group-text");
            spanAddAction.textContent = "+";
            spanAddAction.setAttribute("step", stepLength);
            selectPrependGroup.appendChild(spanAddAction);

            const selectAction = document.createElement("select");
            selectAction.classList.add("form-control");
            selectAction.setAttribute("actionSelect", stepLength);
            selectActionGroup.appendChild(selectAction);
            actionList.forEach(action => {
                    const option = document.createElement("option");
                    option.value = action;
                    option.text = action;
                    selectAction.appendChild(option);
            })
            stepDiv.appendChild(selectActionGroup);
            spanAddAction.addEventListener("click", addActionToStep);                    

            const stepTextArea = document.createElement("textarea");
            stepTextArea.setAttribute("step", stepLength)
            stepTextArea.classList.add("form-control");
            if (expression) {
                stepTextArea.value = expression;
            }
            stepDiv.appendChild(stepTextArea);
        }
        

        function updateActionList(code) {
            try {
                const codeJSON = JSON.parse(code);
                actionList = codeJSON.map(rule => rule.output.prefix);
                const selects = document.querySelectorAll("[actionselect]");
                for (const select of selects) {
                    while(select.hasChildNodes()) {
                        select.firstChild.remove();
                    }
                    actionList.forEach(action => {
                    const option = document.createElement("option");
                    option.value = action;
                    option.text = action;
                    select.appendChild(option);
            })                        }
            } catch(e) {}                    
        }

        function addActionToStep(e) {
            const button = e.target;
            const stepNumber = button.getAttribute("step")
            const action = document.querySelector(`[actionSelect="${stepNumber}"]`).value;
            const value = document.querySelector(`textarea[step="${stepNumber}"]`).value
            
            document.querySelector(`textarea[step="${stepNumber}"]`).value = `${value} ${action}`
        }

        function validation(e) {
            if (stepLength === 0) {
                return true;
            }
            const steps = [];
            try {
                for (let i = 1; i <= stepLength; i++) {
                    if (!document.querySelector(`[stepName="${i}"]`)) {
                        continue;
                    }
                    const name = document.querySelector(`[stepName="${i}"]`).value;
                    const value = document.querySelector(`textarea[step="${i}"]`).value;
                    steps.push({name, value});
                }
                document.getElementById("stepList").value = JSON.stringify(steps);
                console.log(document.getElementById("stepList"))
            } catch(e) {
                console.error(e)
                return false;
            }
            return true;
        }
    </script>
</body>

</html>