{% extends "../template_wider.html" %}
{% block content %}
{% load nearbeach_extras %}
{% load static %}
    <!-- STYLES -->
    <style type="text/css" media="screen">
		div.base {
			position: absolute;
			overflow: hidden;
			font-family: Arial;
			font-size: 8pt;
		}
		div.base#graph {
			border-style: solid;
			border-color: #F2F2F2;
			border-width: 1px;
			background: url('{% static "NearBeach/whiteboard/images/grid.gif" %}');
            width: 100%;
		}
	</style>

    <!-- MX Graph Source Code -->
    <script type="text/javascript" src="{% static 'NearBeach/js/mxClient.min.js' %}"></script>
    <link rel="stylesheet" type="text/css" href="{% static 'NearBeach/whiteboard/css/common.css' %}">

    <!-- MX Graph Settings -->
    <script type="text/javascript">
		mxGraph.prototype.htmlLabels = true;

		mxGraph.prototype.isWrapping = function(cell)
		{
			return true;
		};

		//When the user saves :)
        mxEditor.prototype.urlPost = "{% url 'whiteboard_save' whiteboard_id %}";
        mxEditor.prototype.save = function(url, linefeed) {
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });


            //Get the xml data
            var encoder = new mxCodec();
            var result = encoder.encode(editor.graph.getModel());
            var xml = mxUtils.getXml(result);


            console.log("XML EXTRACT: ",xml);


            $.ajax({
                url: '{% url "whiteboard_save" whiteboard_id %}',
                data: {
                    'whiteboard_xml': xml,
                },
                datatype: 'XML',
                type: 'POST',
                success: function(data) {
                    console.log("YAY");
                },
                error: function() {
                    console.log("FUCK");
                }
            });
        };

        //Load the data
        var xml = `{{ whiteboard_results.whiteboard_xml }}`;
        if (xml != '') {
            var container = document.getElementById("graph"),
                graph = new mxGraph(container),
                diagram = mxUtils.parseXml(xml),
                codec = new mxCodec(diagram);


            console.log("GOT HERE");
            codec.decode(diagram.documentElement, graph.getModel());
            graph.fit();
        }



		mxConstants.DEFAULT_HOTSPOT = 1;

		// Enables guides
		mxGraphHandler.prototype.guidesEnabled = true;

	    // Alt disables guides
	    mxGuide.prototype.isEnabledForEvent = function(evt)
	    {
	    	return !mxEvent.isAltDown(evt);
	    };

		// Enables snapping waypoints to terminals
		mxEdgeHandler.prototype.snapToTerminals = true;

		window.onbeforeunload = function() { return mxResources.get('changesLost'); };
	</script>

	<!-- Loads and initializes the library -->
	<div id="graph" class="base"></div>
	<div id="status" class="base" align="right" style="white-space:nowrap;"></div>

	<!-- Example code -->
	<script type="text/javascript">
        //Global functions
        var editor;

		function createEditor(config) {
            //Try
            try {

                if (!mxClient.isBrowserSupported()) {
                    //mxUtils.error('Browser is not supported!', 200, false);
                    new_error("The Browser is not supported");

                    //Just return
                    return false;
                }


                mxObjectCodec.allowEval = true;
				var node = mxUtils.load(config).getDocumentElement();
                editor = new mxEditor(node);
				mxObjectCodec.allowEval = false;

				// Adds active border for panning inside the container
				editor.graph.createPanningManager = function()
				{
					var pm = new mxPanningManager(this);
					pm.border = 30;

					return pm;
				};

				editor.graph.allowAutoPanning = true;
				editor.graph.timerAutoScroll = true;

				//Load saved data
                var xml = `{{ whiteboard_results.whiteboard_xml|safe }}`,
                    doc = mxUtils.parseXml(xml),
                    codec = new mxCodec(doc);

                //Set XML into the graph
                if (xml != "") {
                    codec.decode(doc.documentElement, editor.graph.getModel());
                }

				// Displays version in statusbar
				editor.setStatus('mxGraph '+mxClient.VERSION);
            } catch (e) {
                new_error(`There was an issue loading the whiteboard: ${e}`);
            }
        }

        mxBasePath = "{% static 'NearBeach/whiteboard' %}";

        $('document').ready(function(){
            createEditor("{% url 'whiteboard_editor_xml' %}");
        });
	</script>
{% endblock %}