{% extends "./template_wider.html" %}
{% block content %}
{% load nearbeach_extras %}
{% load static %}
    <h1>{{ kanban_board_results.kanban_board_name }}</h1>
    <a href="javascript:void(0)" onclick="load_kanban_new_card()">New Card</a><br/>
    <a href="javascript:void(0)" onclick="load_kanban_new_link()">Link Project, Task, or Requirement</a><br/>
    {% for level in kanban_level_results %}
        <!-- SETUP THE CONTAINER FOR LEVEL -->
        <!-- The level heading -->
        <strong>{{ level.kanban_level_name }}</strong>
        <div class="container-fluid">
            <div class="row flex-row flex-nowrap">
                <!-- EACH COLUMN -->
                {% with level_cards=kanban_card_results|filter_level_cards:level.kanban_level_id %}
                    {% for column in kanban_column_results %}
                    <div class="col-3">
                        <div class="card card-block">
                            <div class="card-header">
                                <strong>{{ column.kanban_column_name }}</strong>
                            </div>
                            <div class="card-body kanban_column" data-column="{{ column.kanban_column_id }}" data-level="{{ level.kanban_level_id }}">
                                {% with column_cards=level_cards|filter_column_cards:column.kanban_column_id %}
                                    {% for row in column_cards %}
                                        <div class="list-group-item list-group-item-info kanban_card" id="{{ row.kanban_card_id }}" draggable="true">
                                            {{ row.kanban_card_text }}
                                        </div>
                                    {% endfor %}
                                {% endwith %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                {% endwith %}
            </div>
            <hr>
        </div>
    {% endfor %}


    <!-- THESE WILL CHANGE TO MODALS!! -->




    <!-- MODAL -->
    <!-- NEW CARD FORM -->
    <form id="new_card_form">
        <div class="modal fade" id="new_card_modal" tabindex="-1" role="dialog" aria-labelledby="new_card_modal" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="new_card_modal_title">New Card</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" id="new_card_content">
                        Loading Data...
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" onclick="new_card_submit()" disabled="true" id="new_card_submit_button">Create Card</button>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- EDIT CARD FORM -->
    <form id="edit_card_form">
        <div class="modal fade" id="edit_card_modal" tabindex="-1" role="dialog" aria-labelledby="edit_card_modal" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="edit_card_modal_title">Edit Card</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" id="edit_card_content">
                        Loading Data...
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" onclick="edit_card_submit()" id="edit_card_submit_button">Submit Card Change</button>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- NEW LINKS -->
    <form id="kanban_new_link">
        <div class="modal fade" id="new_link_modal" tabindex="-1" role="dialog" aria-labelledby="new_link_modal" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="new_link_modal_title">Link Project/Task/Requirements</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" id="new_link_content">
                        Loading Data...
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </form>



    <script type="text/javascript">
		$('document').ready(on_page_load());


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

            new_card_submit();
        });



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


        function edit_card_submit() {
            var updated_text = $("#id_kanban_card_text").val(),
                kanban_card_id = $("#edit_kanban_card_id").val(),
                kanban_card = document.getElementById(kanban_card_id),
                new_kanban_card_column = $("#id_kanban_column").val(),
                new_kanban_card_level = $("#id_kanban_level").val(),
                current_kanban_card_column = kanban_card.parentElement.dataset['column'],
                current_kanban_card_level = kanban_card.parentElement.dataset['level'];

            //Update the text :)
            kanban_card.textContent = updated_text;

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

		    $.ajax({
                url: '/kanban_edit_card/' + $("#edit_kanban_card_id").val() + '/',
                type: 'POST',
                data: $("#edit_card_form").serialize(),
                dataType: "HTML",
                success: function(data) {
                    //Close modal
                    $("#edit_card_modal").modal('hide');

                    /*
                    We need to check to see if we require to move the card. We do this by collecting the varibales;
                    - new_kanban_column_id
                    - new_kanban_row_id

                    Then we compare with the current card.

                    If we require them to move, we will then;
                    - move the card to the new location

                    If not - we do nothing.
                    */
                    if (!(new_kanban_card_column == current_kanban_card_column) ||
                        !(new_kanban_card_level == current_kanban_card_level)) {
                        var new_destination = document.querySelector(`[data-column='${new_kanban_card_column}'][data-level='${new_kanban_card_level}']`);
                        new_destination.appendChild(kanban_card);
                    }
                },
                error: function () {
                    new_error("Sorry, saving the card has occurred an error!");
                }
            });
        }


		function load_kanban_new_card() {
		    //We want to bring the modal into focus first
            $("#new_card_modal").modal('show');

		    $.ajax({
                url: '/kanban_new_card/{{ kanban_board_id }}/',
                type: "GET",
                dataType: "HTML",
                success: function(data) {
                    //We want to place the loaded data into the modal
                    $("#new_card_content").html(data);

                    //Focus on the element we want AFTER animation is completed
                    setTimeout(function() {
                        var el = document.getElementById("id_kanban_card_text");
                        el.focus();
                    }, 1000);

                },
                error: function() {
                    new_error("We are sorry, something went wrong with getting the new card ready.");
                }
            })
        }


        function load_kanban_new_link() {
            //Clear the modal
            $("#new_link_content").html("Loading...");

            //Show the modal
            $("#new_link_modal").modal('show');

            //Get the data for the modal
		    $.ajax({
                url: '/kanban_new_link/{{ kanban_board_id }}/',
                type: 'GET',
                dataType: 'HTML',
                success: function(data) {
                    $("#new_link_content").html(data);
                }
            });
        }

        function new_card_submit() {
		    var kanban_column = $("#id_kanban_column").val();
            var kanban_level = $("#id_kanban_level").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_new_card/{{ kanban_board_id }}/',
                type: "POST",
                data: $("#new_card_form").serialize(),
                dataType: "HTML",
                success: function(data) {
                    //Place the new card onto the kanban board
                    /*$(".kanban_column[data-column=" + kanban_column + "][data-level=" + kanban_level + "]").html(
                        $(".kanban_column[data-column=" + kanban_column + "][data-level=" + kanban_level + "]").html() + data
                    );*/

                    $(".kanban_column[data-column=" + kanban_column + "][data-level=" + kanban_level + "]").append(data);

                    //Reset the modal - but hide it first
                    $("#new_card_modal").modal('hide');
                    $("#new_card_content").html('Loading Data...');

                    //We will need the page to re-bind everything
                    on_page_load()
                },
                error: function() {
                    new_error("Sorry, submitting the new card did not work for some reason.")
                }
            })
        }

        function new_card_text_changed() {
            //Disable the submit button if there is no value.
		    $("#new_card_submit_button").prop('disabled', $("#id_kanban_card_text").val() == "")
        }


        function on_page_load(){
            $('.kanban_card').bind('dragstart', function(event) {
                event.originalEvent.dataTransfer.setData("text/plain", event.target.getAttribute('id'));
            });

  		    // bind the dragover event on the board sections
            $('.kanban_column').bind('dragover', function(event) {
                event.preventDefault();
            });

            //Double click
            $('.kanban_card').bind('dblclick', function(event) {
                var kanban_card_id = $(event.target).attr('id');

                //Blank modal
                $("#edit_card_content").html("");

                //Show modal
                $("#edit_card_modal").modal('show');

                //Get data for modal
                $.ajax({
                    url: '/kanban_edit_card/' + kanban_card_id + '/',
                    type: 'GET',
                    dataType: 'HTML',
                    success: function(data) {
                        //Place data into modal
                        $("#edit_card_content").html(data);
                    },
                    error: function() {
                        new_error("Sorry, we can not edit the card at the moment");
                    }
                })
            });



			// bind the drop event on the board sections
  			$('.kanban_column').bind('drop', function(event) {
  			    //Get the current kanban card id
                var kanban_card_id = event.originalEvent.dataTransfer.getData("text/plain");

                /*
                The following target will either be a column (which is what we want), or another kanban card (which is
                what we do not want). This will quickly check to see if the target is a column or a card.
                If it is a kanban card - we will then apply the appendChild function at it's parent
                If it is the column - we will just apply the appendChild function at the target
                 */
                if (event.target.className.includes('kanban_card')) {
                    //The target is at the kanban_card - lets aim for the parent
                    event.target.parentElement.appendChild(document.getElementById(kanban_card_id));
                } else {
                    //The target is at the column... Just append the child here
                    event.target.appendChild(document.getElementById(kanban_card_id));
                }
                event.preventDefault();

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



                $.ajax({
                    url: '/kanban_move_card/' + document.getElementById(kanban_card_id).id + '/' + this.dataset.column + '/' + this.dataset.level + '/',
                    data: {},
                    dataType: 'HTML',
                    type: 'POST',
                    success: function (data) {
                    },
                    error: function(request, error) {
                        new_error("We are sorry. Something went wrong when we moved that card. Reloading page");
                        location.reload()
                    }
                })
			});
        }

        function kanban_link_object(location_id, destination) {
            kanban_column = $("#id_kanban_column").val();
            kanban_level = $("#id_kanban_level").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_new_link/{{ kanban_board_id }}/' + location_id + '/' + destination + '/',
                data: $("#kanban_new_link").serialize(),
                dataType: 'HTML',
                type: 'POST',
                success: function (data) {

                    /*$(".kanban_column[data-column=" + kanban_column + "][data-level=" + kanban_level + "]").html(
                        $(".kanban_column[data-column=" + kanban_column + "][data-level=" + kanban_level + "]").html() + data
                    );*/
                    //Append the data onto the UL
                    $(".kanban_column[data-column=" + kanban_column + "][data-level=" + kanban_level + "]").append(data);

                    //Make sure the objects can now be moved around
                    on_page_load();

                    //Close the modal
                    $("#new_link_modal").modal('hide');
                },
                error: function(data) {
                    new_error("Sorry, the linking of the object didn't work. Please try again.");
                }
            })
        }


    </script>
{% endblock %}