{% extends "base.html" %}

{% load static %}

{% block head %}
    <link rel="stylesheet" href="{% static 'css/leaflet.css' %}"/>
    <script src="{% static 'js/leaflet.js' %}"></script>
    <script src="{% static 'js/pixi.min.js' %}"></script>
    <script src="{% static 'js/L.PixiOverlay.min.js' %}"></script>
{% endblock %}

{% block title %}
    Управление маршрутом (Миссия {{ mission }})
{% endblock %}

{% block content %}
    <form action="" method="GET">
        <div class="row" style="margin-top: 10px;">
            <div class="col"></div>

            <div class="col">
                <label for="fieldName">Оптимизация движения машины</label>
                <select id="fieldName" name="carMove" class="form-control">
                    <option value="no" {% if request.GET.carMove == "no" %}selected{% endif %}>Без оптимизации и движения</option>
                    <option value="start_opt" {% if request.GET.carMove == "start_opt" %}selected{% endif %}>Оптимизация точки старта</option>
                    <option value="simple" {% if request.GET.carMove == "simple" %}selected{% endif %}>Равномерное движение</option>
                    <option value="genetic" {% if request.GET.carMove == "genetic" %}selected{% endif %}>Генетическая оптимизация</option>
                </select>
            </div>

            <div class="col">
                <label for="fieldName">Направление облета</label>
                <select id="fieldName" name="direction" class="form-control">
                    <option value="simple" {% if request.GET.direction == "simple" %}selected{% endif %}>Простая оптимизация</option>
                    <option value="horizontal" {% if request.GET.direction == "horizontal" %}selected{% endif %}>Горизонтальный</option>
                    <option value="vertical" {% if request.GET.direction == "vertical" %}selected{% endif %}>Вертикальный</option>
                    <option value="optimization" {% if request.GET.direction == "optimization" %}selected{% endif %}>EM оптимизация</option>
{#                    <option value="set" {% if request.GET.direction == "set" %}selected{% endif %}>Выбрать</option>#}
                </select>
            </div>

            <div class="col"></div>
        </div>

        <div class="row" style="margin-top: 10px;">
            <div class="col"></div>

            <div class="col">
                <label for="fieldName">Дополнительные функции</label>
                <div class="row">
                    <div class="col">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="heightDiff" id="exampleCheck1" {% if '?' not in request.get_full_path or "heightDiff" in request.GET %}checked{% endif %}>
                            <label class="form-check-label" for="exampleCheck1" style="font-size: 0.75rem;">Развод по высотам</label>
                        </div>

                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="roundStartZone" id="exampleCheck2" {% if '?' not in request.get_full_path or "roundStartZone" in request.GET %}checked{% endif %}>
                            <label class="form-check-label" for="exampleCheck2" style="font-size: 0.75rem;">Облет зон старта по дуге</label>
                        </div>
                    </div>

                    <div class="col">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="feature3" id="exampleCheck3" {% if "feature3" in request.GET %}checked{% endif %}>
                            <label class="form-check-label" for="exampleCheck3" style="font-size: 0.75rem;">Фича 3</label>
                        </div>

                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="feature4" id="exampleCheck4" {% if "feature4" in request.GET %}checked{% endif %}>
                            <label class="form-check-label" for="exampleCheck4" style="font-size: 0.75rem;">Фича 4</label>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col">
                <label for="fieldName">Точка старта</label>
                <select id="fieldName" name="start" class="form-control">
                    <option value="ne" {% if request.GET.start == "ne" %}selected{% endif %}>NE</option>
                    <option value="nw" {% if request.GET.start == "nw" %}selected{% endif %}>NW</option>
                    <option value="sw" {% if request.GET.start == "sw" %}selected{% endif %}>SW</option>
                    <option value="se" {% if request.GET.start == "se" %}selected{% endif %}>SE</option>
                </select>
            </div>

            <div class="col"></div>
        </div>

        <div class="row" style="margin-top: 10px;">
            <div class="col"></div>

            <div class="col">
                <label for="fieldName">Сериализованный объект</label>
                <input id="fieldName" name="serialized" class="form-control" value="{{ request.GET.serialized }}"/>
            </div>

            <div class="col"></div>
        </div>

        <div class="row">
            <div class="col"></div>

            <div class="col" style="text-align: right;">
                <button id="saveField" class="btn btn-primary" style="margin-top: 10px;" name="submitShow">Посмотреть маршрут</button>
            </div>

            <div class="col" style="text-align: left;">
                <button id="saveField" class="btn btn-primary" style="margin-top: 10px;" name="submitSave">Сохранить маршрут</button>
            </div>

            <div class="col"></div>
        </div>
    </form>

    <div id="map" style="height: 700px; margin-top: 10px;"></div>
{% endblock %}

{% block foot %}
    <script>
        function shuffle(array) {
            var currentIndex = array.length, temporaryValue, randomIndex;

            // While there remain elements to shuffle...
            while (0 !== currentIndex) {

                // Pick a remaining element...
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex -= 1;

                // And swap it with the current element.
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;
            }

            return array;
        }

        var colorPallete = [
            "#001f3f", "#0074D9", "#7FDBFF", "#39CCCC",
            "#3D9970", "#2ECC40", "#01FF70", "#FFDC00",
            "#FF851B", "#FF4136", "#85144b", "#F012BE",
            "#B10DC9", "#111111", "#AAAAAA", "#DDDDDD"
        ]
        shuffle(colorPallete);
        for(let i = 0; i < 10; i++){
            colorPallete.concat(colorPallete);
        }

        var False = false;
        var True = true;
        var waypoints;
        var fieldPolygon;
        var gridStep;
        var initial;
        var map;
        var loader;
        var grid;
        var road;
        var tick;
        var project;
        var reverseProject;
        var stage;
        var mission_id = {{ mission.id }};

        function initStuff() {
            fieldPolygon = {{ field|safe }};
            waypoints = {{ waypoints|safe }};
            road = {{ road|safe }};
            for (i = 0; i < fieldPolygon.length; i++) {
                tmp = fieldPolygon[i][0];
                fieldPolygon[i][0] = fieldPolygon[i][1];
                fieldPolygon[i][1] = tmp;
            }
            fieldPolygon.push(fieldPolygon[0]);

            gridStep = {{ grid_step|safe }};

            // prepare circle texture, that will be our brush
            const brush = new PIXI.Graphics();
            brush.beginFill(0xffffff);
            brush.drawCircle(0, 0, 500);
            brush.endFill();

            initial = {{ initial|safe }};
            initial = [initial[1], initial[0]];
            map = L.map('map').setView(initial, 13);
            L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
                attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
                maxZoom: 18,
                id: 'mapbox/streets-v11',
                tileSize: 512,
                zoomOffset: -1,
                accessToken: 'pk.eyJ1Ijoia2luZHlhayIsImEiOiJja2F0cml2eTcwNDZhMnJvOXI4N2Y4MjRjIn0.f7FSJnib2jKKvtJe4ql-Bg'
            }).addTo(map);

            grid = {{ grid|safe }};
            stage = new PIXI.Container();
            loader = new PIXI.Loader();
            loader.load(setupWrapper);
        }

        function setupWrapper(loader, resources) {
            var firstDraw = true;
            var prevZoom;

            var pixiOverlay = L.pixiOverlay(function (utils, event) {
                if(event.type !== 'redraw') {
                    var zoom = utils.getMap().getZoom();
                    var container = utils.getContainer();
                    var renderer = utils.getRenderer();
                    project = utils.latLngToLayerPoint;
                    reverseProject = utils.layerPointToLatLng;
                    var scale = utils.getScale();

                    setup(loader, resources, container, project, scale);

                    firstDraw = false;
                    prevZoom = zoom;
                    renderer.render(container);
                }
            }, stage);
            pixiOverlay.addTo(map);

            let ticker = new PIXI.Ticker();
            ticker.autoStart = false;
            ticker.stop()
            let renderer = PIXI.autoDetectRenderer();
            ticker.add(function (time) {
                {#gameLoop(time);#}
                pixiOverlay.redraw({type: "redraw", delta: time});
            });
            {#ticker.minFPS = 5;#}
            {#ticker.maxFPS = 60;#}
            ticker.start();
        }

        function setup(loader, resources, stage, project, scale) {
            let latLng = initial.slice();
            let coords = project(latLng);
            {#const background = new PIXI.Sprite(resources.badland.texture);#}
            {#stage.addChild(background);#}
            {#background.width = 1;#}
            {#background.height = 1;#}
            {#background.x = coords.x;#}
            {#background.y = coords.y;#}

            let field = new PIXI.Graphics();
            field.beginFill(0);

            // Draw grid
            for (let point of grid) {
                let circle = L.circle([point[1], point[0]], {
                    color: '#da3e28',
                    fillOpacity: 0.5,
                    radius: 9
                }).addTo(map);
            }

            // Draw polygon
            var polyline = L.polyline(fieldPolygon, {color: 'red'}).addTo(map);

            // Draw road
            for (let i=0; i < road.length - 1; i++) {
                let curPoint = road[i];
                while(Math.sqrt((curPoint[0] - road[i+1][0])*(curPoint[0] - road[i+1][0]) + (curPoint[1] - road[i+1][1])*(curPoint[1] - road[i+1][1])) > 0.0015){
                    let delta_x = road[i+1][0] - curPoint[0];
                    let delta_y = road[i+1][1] - curPoint[1];
                    let delta = Math.sqrt(delta_x * delta_x + delta_y * delta_y);
                    delta_x /= delta;
                    delta_y /= delta;

                    curPoint[0] += delta_x * 0.001;
                    curPoint[1] += delta_y * 0.001;

                    let circle = L.circle([curPoint[1], curPoint[0]], {
                        color: '#5e4b7f',
                        fillOpacity: 0.9,
                        radius: 100
                    }).addTo(map);
                }
            }

            // Draw waypoints
            i = 0;
            for(let drone_waypoints of waypoints){
                L.polyline(drone_waypoints, {
                    color: colorPallete[i],
                    weight: 2.5,
                    smoothFactor: 1
                    }).addTo(map);
                i += 1;
            }

            return stage;
        }

        initStuff();
    </script>
{% endblock %}
