{% extends "../template.html" %}
{% block content %}
{% load static %}
    <style>
        .drag_element {
            opacity: 0.4;
        }

        .over {
            border-top: 2px solid blue;
        }
    </style>
    <form method="post" class="kanban_board_form" id="kanban_properties_form">
        <div class="card mt-4">
            <div class="card-header">
                <h2>Kanban Properties</h2>
            </div>
            <div class="card-body">
                {% csrf_token %}
                {{ kanban_properties_form.kanban_board_name }}
                <div class="row">
                    <div class="card col-6 mt-4">
                        <div class="card-header">
                            <h3>Columns</h3>
                            <p>Please sort the columns in the order you would like them to appear on the board. Click on them to either change their name or delete them. Please note - only empty columns can be deleted.</p>
                        </div>
                        <div class="card-body">
                            <table>
                                <tr>
                                    <td>
                                        <ul id="columns">
                                            {% for row in kanban_column_results %}
                                                <li class="column_title"
                                                    draggable="true"
                                                    data-id="{{ row.kanban_column_id }}"
                                                    value="{{ row.kanban_column_id }}"
                                                    ondblclick="open_modal('column','{{ row.kanban_column_id }}')"
                                                >{{ row.kanban_column_name }}</li>
                                            {% endfor %}
                                        </ul>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="card col-6 mt-4">
                        <div class="card-header">
                            <h3>Levels</h3>
                            <p>Please sort the levels in the order you would like them to appear on the board. Click on them to either change their name or delete them. Please note - only empty levels can be deleted.</p>
                        </div>
                        <div class="card-body">
                            <table>
                                <tr>
                                    <td>
                                        <ul id="levels">
                                            {% for row in kanban_level_results %}
                                                <li class="level_title"
                                                    draggable="true"
                                                    data-id="{{ row.kanban_level_id }}"
                                                    value="{{ row.kanban_level_id }}"
                                                    ondblclick="open_modal('level','{{ row.kanban_level_id }}')"
                                                >{{ row.kanban_level_name }}</li>
                                            {% endfor %}
                                        </ul>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <input id="save_changes" type="submit" value="Save Changes" class="btn btn-primary col-6">
                    <a href="{% url 'search_kanban' %}" class="btn btn-warning col-6">Cancel and Return</a>
                </div>
            </div>
        </div>
    </form>

    {% if permission >= 3 %}
        <div class="card mt-4">
            <div class="card-header">
                <h2>Assigned Groups</h2>
            </div>
            <div class="card-body">
                <form method="post" class="assigned_groups" id="assigned_groups">
                    Loading add...
                </form>
                <div id="assigned_group_list">Loading list...</div>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header bg-danger">
                <h2>DANGER ZONE!</h2>
            </div>
            <div class="card-body">
                <button class="btn btn-warning form-control" onclick="open_close_kanban_module()">
                    Close Kanban Board
                </button>
            </div>
        </div>
    {% endif %}

    <div class="modal" tabindex="-1" role="dialog" id="name_change_modal">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <!-- HEADER -->
                <div class="modal-header">
                    <h5 class="modal-title">Change Column Name</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <!-- BODY -->
                <div class="modal-body">
                    <input id="column_or_level" hidden />
                    <input id="object_id" hidden />
                    <div class="form-group">
                        <label for="new_name">New Name</label>
                        <input id="new_name" class="form-control" type="text" onkeyup="disable_modal_save_button()" />
                    </div>
                </div>


                <!-- FOOTER -->
                <div class="modal-footer">
                    <button type="button" id="modal_save" class="btn btn-primary" onclick="update_name()" disabled>Save</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- CLOSE KANBAN MODAL -->
    <div class="modal" tabindex="-1" role="dialog" id="close_kanban_modal">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <!-- HEADER -->
                <div class="modal-header">
                    <h5 class="modal-title">Close Kanban</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <!-- BODY -->
                <div class="modal-body">
                    <p>Are you sure you want to close this kanban board?</p>
                </div>


                <!-- FOOTER -->
                <div class="modal-footer">
                    <!-- ADD IN BUTTONS -->
                    <button type="button" id="kanban_close_button" class="btn btn-danger" onclick="close_kanban()" disabled="">Close Kanban</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>


    <script>
        //Page variables
        var drag_source_element = null;

        $("#assigned_groups").on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: '/assigned_group_add/{{ kanban_board_id }}/kanban_board/',
                data: $(this).serialize(),
                success: function() {
                    load_assigned_group_add();
                    load_assigned_group_list();
                },
                error: function() {
                    new_error("Sorry, project assigned users did not save. Please try again.");
                }
            })
        });


        $("#kanban_properties_form").on('submit', function(event) {
            event.preventDefault();

            //Get the JSON data ready
            var columns = $("#columns").find("li").map(function() {
                var column = {};

                column.id = this.value;
                column.title = $(this).text();

                return column;
            });


            //Get the JSON data ready
            var levels = $("#levels").find("li").map(function() {
                var level = {};

                level.id = this.value;
                level.title = $(this).text();

                return level;
            });


            data_to_send = {
                "columns": columns,
                "levels": levels,
                "kanban_board_name": ($("#id_kanban_board_name").val())
            };


            //Send data to the database
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                url: '/kanban_properties/{{ kanban_board_id }}/',
                type: 'POST',
                dataType: 'HTML',
                data: JSON.stringify(data_to_send),
                success: function(data) {
                    //On Success, take the user to the kanban board list
                    window.location = '/search_kanban/'
                },
                error: function () {
                    new_error("SORRY");
                }
            });
        });

        function handle_drag_start(element) {
            // Set the drag source element as this element
            drag_source_element = this;

            element.dataTransfer.effectAllowed = 'move';
            element.dataTransfer.setData('text/html', this.outerHTML);

            this.classList.add('drag_element');
        }

        function handle_drag_over(element) {
            if (element.preventDefault) {
                element.preventDefault();
            }

            this.classList.add('over');

            element.dataTransfer.dropEffect = 'move';

            return false;
        }

        function handle_drag_enter(element) {
            //Left empty at the moment.
        }

        function handle_drag_leave() {
            this.classList.remove('over');
        }

        function handle_drop(element) {
            if (element.stopPropagation) {
                element.stopPropagation(); // Stops from redirecting
            }

            // Don't need to do anything if dropping in the same column
            if (drag_source_element != this) {
                this.parentNode.removeChild(drag_source_element);
                var dropHTML = element.dataTransfer.getData('text/html');
                this.insertAdjacentHTML('beforebegin', dropHTML);
                var drop_element = this.previousSibling;
                add_DnD_handlers(drop_element);
            }

            this.classList.remove('over');
            return false;
        }

        function handle_drag_end() {
            this.classList.remove('over');
        }


        function add_DnD_handlers(element) {
            //DnD is not dungeons and dragons
            element.addEventListener('dragstart', handle_drag_start, false);
            element.addEventListener('dragenter', handle_drag_enter, false);
            element.addEventListener('dragover', handle_drag_over, false);
            element.addEventListener('dragleave', handle_drag_leave, false);
            element.addEventListener('drop', handle_drop, false);
            element.addEventListener('dragend', handle_drag_end, false);
        }

        //Find all the column elements and give them the ability to drag and drop
        var cols = document.querySelectorAll('#columns .column_title');
        [].forEach.call(cols,add_DnD_handlers);

        var levels = document.querySelectorAll('#levels .level_title');
        [].forEach.call(levels,add_DnD_handlers);

        function load_assigned_group_add() {
            $.ajax({
                url: '/assigned_group_add/{{ kanban_board_id }}/kanban_board/',
                data: {},
                dataType: 'HTML',
                type: 'GET',
                success: function(data) {
                    $('#assigned_groups').html(data);
                },
                error: function() {
                    $('#assigned_groups').html('<h2>Assigned Groups</h2>Sorry, assigned groups encounted an error and did not load.');
                }
            });
        };

        function delete_group_item(group_item) {
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                url: '/assigned_group_delete/' + group_item + '/',
                data: {},
                dataType: 'HTML',
                type: 'POST',
                success: function(data) {
                    load_assigned_group_add();
                    load_assigned_group_list();                },
                error: function() {
                    new_error("Sorry, there was an issue deleting the Assigned Group")
                }
            });
        };


        function load_assigned_group_list() {
            $.ajax({
                url: '/assigned_group_list/{{ kanban_board_id }}/kanban_board/',
                data: {},
                dataType: 'HTML',
                type: 'GET',
                success: function(data) {
                    $('#assigned_group_list').html(data);
                },
                error: function() {
                    $('#assigned_group_list').html('<h2>Assigned Groups</h2>Sorry, assigned groups encounted an error and did not load.');
                }
            });
        }

        function open_close_kanban_module() {
            //Open the module

            $("#close_kanban_modal").show();

            //Wait 2 seconds before allowing user to close the kanban board
            setTimeout(function() {
                //Find the close element.
                var elem = document.getElementById("kanban_close_button");

                if (elem) {
                    elem.disabled = false;
                }
            },2000);

        }

        function close_kanban() {
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                url: '/kanban_board_close/{{ kanban_board_id }}/',
                data: {},
                dataType: 'HTML',
                type: 'POST',
                success: function(data) {
                    window.location.href = '/search_kanban';
                },
                error: function() {
                    console.log("ERROR");
                }
            })
        }

        function open_modal(column_or_level,id) {
            //Open up the model for changing the name.
            //alert("CLICK WORKED");
            var col = document.getElementById("column_or_level"),
                object_id = document.getElementById("object_id"),
                new_name = document.getElementById("new_name");

            col.value = column_or_level;
            object_id.value = id;
            new_name.value = "";

            $("#name_change_modal").show();
        }

        function update_name() {
            //$("#name_change_modal").hide();

            //Get the variable data
            var column_or_level = document.getElementById("column_or_level").value,
                id = document.getElementById("object_id").value,
                new_name = document.getElementById("new_name").value;

            console.log("Column or level: ",column_or_level);

            if (column_or_level == "column") {
                //Get the column element
                /*
                On a flight at the moment - forgot how to do proper xpath to find the exact element with the data attribute
                id of id. This is a work around :'(
                 */
                var columns = document.getElementById("columns").getElementsByTagName("li"),
                    elem = "";

                for (var i=0; i < columns.length; i++) {
                    if (columns[i]["dataset"]["id"] == id) {
                        //There is a match. Set elems to this element
                        elem = columns[i];
                    }
                }
            } else if (column_or_level == "level") {
                //Get the level
                var levels = document.getElementById("levels").getElementsByTagName("li"),
                    elem = "";

                for (var i=0; i < levels.length; i++) {
                    if (levels[i]["dataset"]["id"] == id) {
                        //There is a match. Set elems to this element
                        elem = levels[i];
                    }
                }

            } else {
                //Something went wrong
                return;
            }

            //If there is no element return error
            if (elem == "") {
                alert("There was an error trying to save the name");
                return;
            }

            //Update the field name
            elem.innerText = new_name;

            $("#name_change_modal").hide();
        }

        function disable_modal_save_button() {
            if ($("#new_name").value == "") {
                //Nothing in new name - disable the button
                $("#modal_save").prop("disabled",true);
            } else {
                //Something is in the new name - enable the button
                $("#modal_save").prop("disabled",false);
            }
        }


        load_assigned_group_list();
        load_assigned_group_add();
    </script>


{% endblock %}