<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CORE</title>
    <link rel="stylesheet" type="text/css" href="static/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="static/vis.min.css">
    <link rel="stylesheet" type="text/css" href="static/toastr.min.css">
    <link rel="stylesheet" type="text/css" href="static/core.css">
</head>
<body>
<div class="container-fluid d-flex flex-column p-0">
    <nav class="navbar navbar-expand navbar-dark bg-dark mb-2">
        <div class="navbar-brand mb-0 h1">
            <img src="static/core-icon.png"/>
            <span>CORE</span>
        </div>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#nb-content"
                aria-controls="nb-content" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="nb-content">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="nb-file" role="button" data-toggle="dropdown"
                       aria-haspopup="true" aria-expanded="false">
                        File
                    </a>
                    <div class="dropdown-menu" aria-labelledby="nb-file">
                        <label class="dropdown-item btn btn-default">
                            Open Session <input id="session-open" type="file" hidden>
                        </label>
                        <a id="session-save-button" class="dropdown-item" href="#">Save Session</a>
                    </div>
                </li>

                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="nb-session" role="button" data-toggle="dropdown"
                       aria-haspopup="true" aria-expanded="false">
                        Sessions
                    </a>
                    <div class="dropdown-menu" aria-labelledby="nb-session">
                        <a id="new-session-button" class="dropdown-item" href="#">New</a>
                        <a class="dropdown-item" href="#" data-toggle="modal" data-target="#sessions-modal">View</a>
                    </div>
                </li>

                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="nb-help" role="button" data-toggle="dropdown"
                       aria-haspopup="true" aria-expanded="false">
                        Help
                    </a>
                    <div class="dropdown-menu" aria-labelledby="nb-help">
                        <a class="dropdown-item" href="https://github.com/coreemu/core">GitHub</a>
                        <a class="dropdown-item" href="http://coreemu.github.io/core/">Documentation</a>
                    </div>
                </li>
            </ul>

            <span id="session-id" class="navbar-text p-2 mr-3">Session #</span>
            <div>
                <span id="node-display" class="navbar-text p-2">Create:</span>
                <img id="node-select" src="static/router.svg"/>
            </div>
        </div>
    </nav>

    <div class="row col">
        <div class="col-3 col-xl-2">
            <div class="btn-group-vertical w-100" role="group" aria-label="Side Menu">
                <button id="run-button" type="button" class="btn btn-success">Start</button>
                <button id="link-button" type="button" class="btn btn-secondary" data-toggle="button">Link Mode</button>
                <div class="btn-group dropright node-buttons" role="group">
                    <button id="menu-nodes" type="button" class="btn btn-secondary dropdown-toggle"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Nodes
                    </button>
                    <div class="dropdown-menu" aria-labelledby="menu-nodes">
                        <a class="dropdown-item" href="#" data-node="0" data-model="router">Router</a>
                        <a class="dropdown-item" href="#" data-node="0" data-model="host">Host</a>
                        <a class="dropdown-item" href="#" data-node="0" data-model="PC">PC</a>
                        <a class="dropdown-item" href="#" data-node="0" data-model="mdr">MDR</a>
                    </div>
                </div>
                <div class="btn-group dropright node-buttons" role="group">
                    <button id="menu-devices" type="button" class="btn btn-secondary dropdown-toggle"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Devices
                    </button>
                    <div class="dropdown-menu" aria-labelledby="menu-devices">
                        <a class="dropdown-item" href="#" data-node="5">Hub</a>
                        <a class="dropdown-item" href="#" data-node="4">Switch</a>
                        <a class="dropdown-item" href="#" data-node="6">WLAN</a>
                        <a class="dropdown-item" href="#" data-node="10">EMANE</a>
                    </div>
                </div>
            </div>

            <div id="info-card" class="card text-white bg-dark mt-3 invisible">
                <div id="info-card-header" class="card-header">Selected Title</div>
                <div class="card-body p-0">
                    <table id="info-card-table" class="table mb-0">
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div id="core-network" class="col">
        </div>
    </div>
</div>

{% include 'sessions_modal.html' %}
{% include 'nodeedit_modal.html' %}
{% include 'linkedit_modal.html' %}
{% include 'service_modal.html' %}
{% include 'services_modal.html' %}
{% include 'config_modal.html' %}

<div id="node-context" class="list-group context d-none">
    <button type="button" class="list-group-item list-group-item-action" data-option="edit">Edit Node</button>
    <button id="node-linkrf-button" type="button" class="list-group-item list-group-item-action d-none"
            data-option="linkrf">Link All Routers
    </button>
    <button type="button" class="list-group-item list-group-item-action" data-option="services">Services</button>
    <button id="node-delete-button" type="button" class="list-group-item list-group-item-action" data-option="delete">
        Delete
    </button>
</div>

<div id="edge-context" class="list-group context d-none">
    <button type="button" class="list-group-item list-group-item-action" data-option="edit">Edit Link</button>
</div>

<script src="static/jquery-3.3.1.min.js"></script>
<script src="static/popper.min.js"></script>
<script src="static/bootstrap.min.js"></script>
<script src="static/vis.min.js"></script>
<script src="static/toastr.min.js"></script>
<script src="static/socket.io.js"></script>
<script src="static/coreip.js"></script>
<script src="static/corerest.js"></script>
<script src="static/corenetwork.js"></script>
<script src="static/coreui.js"></script>

<script>
    // configure global toastr
    console.log(toastr.options);
    toastr.options.timeOut = 2000;
    toastr.options.positionClass = 'toast-bottom-right';

    const $linkButton = $('#link-button');
    const $nodeButtons = $('.node-buttons a');
    const $sessionId = $('#session-id');
    const $nodeDisplay = $('#node-display');
    const $runButton = $('#run-button');
    const $nodeSelect = $('#node-select');
    const $newSessionButton = $('#new-session-button');
    const $sessionSaveButton = $('#session-save-button');
    const $sessionOpen = $('#session-open');

    function formToJson($form) {
        const formData = {};
        $form.serializeArray().map(function (x) {
            let value = x.value;
            if (value === '') {
                value = null;
            } else if (!isNaN(value)) {
                value = parseInt(value);
            }
            formData[x.name] = value;
        });
        return formData;
    }

    // core setup
    const coreRest = new CoreRest();
    const coreNetwork = new CoreNetwork('core-network', coreRest);
    const serviceModal = new ServiceModal(coreRest);
    const servicesModal = new ServicesModal(coreRest, coreNetwork, serviceModal);
    const sessionsModal = new SessionsModal(coreRest, coreNetwork, joinSession, initialSetup);
    const nodeEditModal = new NodeEditModal(coreNetwork, coreRest);
    const nodeContext = new NodeContext(coreNetwork, coreRest, nodeEditModal, servicesModal);
    const edgeEditModal = new EdgeEditModal(coreNetwork, coreRest);
    const edgeContext = new EdgeContext(coreNetwork, edgeEditModal);
    const infoPanel = new InfoPanel(coreNetwork);
    const configModal = new ConfigModel(coreRest);

    function initialSetup() {
        coreNetwork.initialSession()
                .then(function (session) {
                    joinSession(session);
                })
                .catch(function (err) {
                    console.log('initial session error: ', err);
                });
    }

    function setRunButton(start) {
        console.log('set run button: ', start);
        const $runButton = $('#run-button');
        $runButton.removeClass('btn-danger btn-success');
        if (start) {
            $runButton.text('Start');
            $runButton.addClass('btn-success');
            $linkButton.removeAttr('disabled');
        } else {
            $runButton.text('Stop');
            $runButton.addClass('btn-danger');
            $linkButton.removeClass('active');
            $linkButton.attr('disabled', 'disabled');
            coreNetwork.linkMode(false);
        }
    }

    function joinSession(session) {
        $sessionId.text(`Session: ${session.id}`);
        const isStartEnabled = session.state !== SessionStates.runtime;
        setRunButton(isStartEnabled);
        $sessionSaveButton.attr('href', `/sessions/${session.id}/xml`);
        $sessionSaveButton.attr('download', true);
    }

    initialSetup();

    // handle network clicks
    coreNetwork.network.on('click', function (properties) {
        console.log('click properties: ', properties);
        nodeContext.hide();
        edgeContext.hide();

        if (properties.nodes.length === 1) {
            const nodeId = properties.nodes[0];
            infoPanel.showNode(nodeId);
        } else if (properties.edges.length === 1) {
            const edgeId = properties.edges[0];
            infoPanel.showEdge(edgeId);
        } else {
            infoPanel.hide();
        }
    });

    coreNetwork.network.on('oncontext', function (properties) {
        console.log('context event: ', properties);
        properties.event.preventDefault();
        nodeContext.hide();
        edgeContext.hide();

        const location = properties.pointer.DOM;
        const x = properties.event.pageX;
        const y = properties.event.pageY;

        const nodeId = coreNetwork.network.getNodeAt(location);
        if (nodeId) {
            nodeContext.show(nodeId, x, y)
                    .catch(function (err) {
                        console.log('error showing node context: ', err);
                    });
        } else {
            const edgeId = coreNetwork.network.getEdgeAt(location);
            if (edgeId) {
                edgeContext.show(edgeId, x, y);
            }
        }
    });

    $newSessionButton.click(function () {
        coreNetwork.newSession()
                .then(function (session) {
                    joinSession(session);
                })
                .catch(function (err) {
                    console.log('error creating new session: ', err);
                });
    });

    $linkButton.click(function () {
        const linkMode = !$(this).hasClass('active');
        coreNetwork.linkMode(linkMode);
        $(this).blur();
    });

    $runButton.click(function () {
        const $this = $(this);
        const start = $this.text() === 'Start';
        if (start) {
            coreNetwork.start()
                    .then(function () {
                        setRunButton(false);
                    })
                    .catch(function (err) {
                        console.log('start error: ', err);
                    });
        } else {
            coreRest.shutdownSession()
                    .then(function (response) {
                        console.log('shutdown session: ', response);
                        setRunButton(true);
                    })
                    .catch(function (err) {
                        console.log('shutdown error: ', err);
                    });
        }
    });

    $nodeButtons.click(function () {
        const $this = $(this);
        const nodeType = $this.data('node');
        const model = $this.data('model');
        console.log('node creation: ', nodeType, model);
        console.log('clicked: ', this);
        coreNetwork.setNodeMode(nodeType, model);
        const currentType = CoreNodeHelper.getDisplay(coreNetwork.nodeType);
        const defaultType = CoreNodeHelper.getDisplay(CoreNodeHelper.defaultNode);
        let nodeName = currentType.name;
        if (currentType.display === defaultType.display) {
            nodeName = coreNetwork.nodeModel;
        }
        const icon = CoreNodeHelper.icons[nodeName];
        $nodeSelect.attr('src', icon);
    });

    $sessionOpen.change(function (event) {
        const file = event.target.files[0];
        console.log('session open: ', file);
        const uri = `/sessions/xml`;
        const request = new XMLHttpRequest();
        const formData = new FormData();
        request.open('POST', uri, true);
        request.onreadystatechange = function () {
            if (request.readyState == 4 && request.status == 200) {
                const response = JSON.parse(request.responseText);
                coreNetwork.joinSession(response.id)
                        .then(function (session) {
                            joinSession(session);
                        })
                        .catch(function (err) {
                            console.log('join open session error: ', err);
                        });
            }
        };
        formData.append('session', file);
        request.send(formData);
    });

    console.log('connecting to ws');
    const ws = io.connect();
    ws.on('connection', function () {
        console.log('connected!');
    });
    ws.on('error', function (error) {
        console.log(error);
    });

    ws.on('info', function (data) {
        console.log(data.message);
    });

    ws.on('node', function (data) {
        console.log(data);
    });
</script>
</body>
</html>
