{% extends "base.html" %}
<!-- Load Internationalization utils-->
{% load i18n %}
{% load l10n %}
{% load static %}
{% load rules %}

{% block title %}{% trans "Edit delivery:" %}: {{ delivery_history.route.name }} {% endblock %}

{% block extrahead %}
    {% load leaflet_tags %}
    {% leaflet_css %}
    <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet">
{% endblock %}

{% block content %}
{% has_perm 'sous_chef.edit' request.user as can_edit_data %}

{% include 'kitchen_count_steps.html' with step='routes' %}

<div class="ui secondary pointing fluid menu">
    <h1 class="ui header">{% trans "Edit delivery:" %} {{ delivery_history.route.name }} </h1>
    <div class="right menu">
      <div class="ui item"><h3><i class="calendar icon"></i>{{ delivery_date }}</h3></div>
    </div>
</div>

<div class="ui basic segment no-print">
    <a href="javascript:printMapAndItinerary()" class="ui labeled icon right pink basic big button" title="{% trans 'Print the map and directions' %}">
        <i class="print icon"></i>{% trans 'Map and Directions' %}
    </a>
</div>

<div class="sixteen wide column">
  <form action="" method="post" class="ui form {% if form.errors %}error{% endif %}" id="delivery-history-edit-form">{% csrf_token %}
    {% if form.errors %}
    <div class="ui error message">
      <div class="header">{% trans 'Required information missing' %}</div>
      <p>{% trans 'Please review the form to make sure that all required fields are filled.' %}</p>
      {{ form.errors }}
    </div>
    {% endif %}
    <div class="field {% if form.vehicle.errors %}error{% endif %}">
      <label>{% trans 'Delivery vehicle of the day' %} ({% trans "default vehicle:" %} {{ delivery_history.route.get_vehicle_display }})</label>
      {{ form.vehicle }}
    </div>

    <div class="field {% if form.client_id_sequence.errors %}error{% endif %}">
      <input type="hidden" value="" name="client_id_sequence" id="id_client_id_sequence">
      <label>{% trans 'Delivery sequence of the day' %}<i class="help-text question grey icon link" data-content='{% trans 'Dragging a row in the table to change the delivery sequence of the client. Changes will not be saved until clicking "Save" button. By default, it loads the default sequence of the route.' %}'></i></label>

      <table class="ui table striped">
        <thead>
          <tr>
            <th>#</th>
            <th>{% trans 'Name' %}</th>
            <th>{% trans 'Status' %}</th>
            <th>{% trans 'Delivery type' %}</th>
            <th>{% trans 'View order' %}</th>
            <th>{% trans 'Address' %}</th>
            <th>{% trans 'Status' %}<i class="help-text question grey icon link" data-content="{% trans 'Configured, edited or unconfigured.' %}"></i></th>
          </tr>
        </thead>
        <tbody id="clients-on-delivery-history">
          {% for client in clients_on_delivery_history %}
          <tr data-latitude="{{ client.member.address.latitude|unlocalize }}"
              data-longitude="{{ client.member.address.longitude|unlocalize }}"
              data-id="{{ client.pk }}"
              {% if client.status != 'A' %}class="error"{% endif %}>
            <td data-property="delivery_sequence">{{ forloop.counter }}</td>
            <td data-property="name"><a href="{% url 'member:client_information' pk=client.pk %}" title="{% trans "Access the client's file" %}">{{ client.member.firstname }} {{ client.member.lastname }}</a></td>
            <td>{{ client.get_status_display }}</td>
            <td>{{ client.get_delivery_type_display }}</td>
            <td>
              {% if client.order_of_the_day %}
              <a href="{% url 'order:view' client.order_of_the_day.pk %}" title="{% trans "View the order" %}">{% trans 'Order #' %}{{ client.order_of_the_day.pk }}</a>
              {% else %}
                {% trans "[DELETED]" %}
              {% endif %}
            </td>
            <td data-property="address">{{ client.member.address }}</td>
            <td data-property="status">
              {% if client.has_been_configured %}
               <i class="checkmark icon" title="{% trans 'Configured' %}"></i>
              {% else %}
               <i class="remove icon" title="{% trans 'Unconfigured' %}"></i>
              {% endif %}
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>


    <div class="ui field">
          <label>{% trans 'Delivery Preview' %}</label>
          {% leaflet_map "delivery_history_edit_map" callback="__map_init" %}
          <script type="text/javascript">
            function __map_init (map, options) {
              var $vehicle = $('#id_vehicle');
              function _getWaypoints () {
                var waypoints = [
                  [
                    45.516564, -73.575145, {
                      popup_html: "<div class='ui list'>"
                        + "<div class='item'><i class='food icon'></i> Santropol Roulant </div>"
                        + "</div>",
                      icon: L.AwesomeMarkers.icon({icon: 'cutlery', prefix: 'fa', markerColor: 'red', iconColor: '#f28f82'})
                    }
                  ]
                ];
                $("#clients-on-delivery-history > tr").each(function (idx, tr) {
                  var latitude = parseFloat($(tr).data('latitude'));
                  var longitude = parseFloat($(tr).data('longitude'));
                  waypoints.push([
                    latitude, longitude, {
                      popup_html: "<div class='ui list'>"
                        + "<div class='item'><i class='user icon'></i><div class='content'>" + $(tr).find('[data-property="name"]').text() + " (#" + (idx+1).toString() + ")" + "</div></div>"
                        + "<div class='item'><i class='home icon'></i><div class='content'>" + $(tr).find('[data-property="address"]').text() + "</div></div>"
                        + "</div>",
                      icon: L.icon.glyph({
                        prefix: '',
                        glyph: (idx+1).toString()
                      })
                    }
                  ]);
                });
                waypoints.push([waypoints[0][0], waypoints[0][1], {}]);  // Back to Santropol.
                return waypoints;
              }

              sous_chef_leaflet_map_init(map, options, {
                vehicle: $vehicle.val(),
                addListenerOnVehicleChange: function (callback) {
                  $vehicle.on('change', function () {
                    callback($vehicle.val());
                  });
                },
                waypoints: _getWaypoints(),
                addListenerOnWaypointsUpdate: function (setWaypoints) {
                  var sortable = Sortable.create($('#clients-on-delivery-history')[0], {
                    handle: 'tr',
                    draggable: 'tr',
                    onUpdate: function (e) {
                      $(e.item).find('[data-property="status"]').html('<i class="edit icon"></i>');
                      $("#clients-on-delivery-history > tr").each(function (idx, tr) {
                        $(tr).find('[data-property="delivery_sequence"]').text(idx+1);
                      });
                      setWaypoints(_getWaypoints());
                    }
                  });
                  $('#clients-on-delivery-history').data('sortable', sortable);
                  $('#clients-on-delivery-history').data('afterSort', function () {
                    $("#clients-on-delivery-history > tr").each(function (idx, tr) {
                      $(tr).find("[data-property='status']").html('<i class="edit icon"></i>');
                      $(tr).find("[data-property='delivery_sequence']").append(" &rarr; " + (idx+1).toString());
                    });
                    setWaypoints(_getWaypoints());
                  });
                },
                onRoutesfound: function (e) {
                  $("#delivery_history_edit_map").data("routeResult", e.routes[0]);
                }
              });
            }
          </script>
    </div>

    <div class="field {% if form.comments.errors %}error{% endif %}">
      <label>{% trans 'Additional comments of the day' %}</label>
      {{ form.comments }}
    </div>

    <div class="ui row">
      <input type="hidden" name="delivery_date" value="{{ delivery_date.isoformat }}">
      <button class="ui big yellow button" type="submit">{% trans "Save" %}</button>
      <a href="{% url 'delivery:routes' %}?delivery_date={{ delivery_date.isoformat }}" class="ui big gray button">
        {% trans 'Cancel' %}
      </a>
    </div>
  </form>
</div>

<script type="x-tmpl-mustache" id="print-template">
  {% comment %}The print window is managed by JavaScript (using Mustache template system). Below is the page template.{% endcomment %}
  <!DOCTYPE html>
  <html>
    <head>
      <title>{% trans "Delivery of the day" %}: {{ delivery_history.route.name }} - {% now "j F Y" %}</title>
      <meta charset="utf-8">
      <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet">
      {% leaflet_css %}
      <link href="{% static 'css/main.min.css' %}" type="text/css" rel="stylesheet">
      <style>
        hr {margin-top:2em;margin-bottom:2em}
        #directions td:last-child {white-space:nowrap}
      </style>
    </head>
    <body style="width: {% verbatim %}{{ map_width }}{% endverbatim %}px;" other=" height:100%; overflow:auto">
      <h1>{% trans "Delivery of the day" %}: {{ delivery_history.route.name }}</h1>
      <h4>{% now "j F Y" %}</h4>
      <br/>
      <div>
        <button class="no-print" onclick="window.print()">{% trans 'Print' %}</button>
      </div>

      {% verbatim %}
      <div style="height: {{ map_height }}px; width: {{ map_width }}px; position:relative; overflow:hidden">
        <div style="position:absolute; left: {{ pane_left }}px; top: {{ pane_top }}px;">
        {{#map_imgs}}
          <img src="{{ src }}" style="position:absolute; top: {{ top }}px; left: {{ left }}px">
        {{/map_imgs}}

        {{{ map_route_svg }}}

        {{#markers}}
          <div style="position:absolute; top:0; left:0">{{{ html }}}</div>
        {{/markers}}
        </div>
      </div>
      {% endverbatim %}

      <hr />

      <h2>{% trans 'Route Sequence' %}</h2>
      <br />
      <h4>{% verbatim %}{{ distance }}{% endverbatim %} {% trans 'kilometers' %}, {% verbatim %}{{ time }}{% endverbatim %} {% trans 'minutes' %} ({% verbatim %}{{ vehicle }}{% endverbatim %})</h4>
      <br />
      <table style="width: 100%">
        <thead>
          <tr>
            <th></th>
            <th style="text-align:left">{% trans 'Client Name' %}</th>
            <th style="text-align:left">{% trans 'Address' %}</th>
          </tr>
        </thead>
        {% verbatim %}
        <tbody>
          {{#routes}}
          <tr>
            <th>{{ client_order }}</th>
            <td>{{ client_name }}</td>
            <td>{{ client_address }}</td>
          </tr>
          {{/routes}}
        </tbody>
        {% endverbatim %}
      </table>
    </body>
  </html>
</script>
{% endblock %}

{% block extrajs %}
    {% leaflet_js %}
    {% if debug %}
        <script src="{% static 'js/leaflet.js' %}" type="application/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
    {% else %}
        <script src="{% static 'js/leaflet.min.js' %}" type="application/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
    {% endif %}
    <script>
      $(function () {
        $("#delivery-history-edit-form").on('submit', function () {
          var client_id_sequence = [];
          $('#clients-on-delivery-history tr').each(function (idx, tr) {
            var id = $(tr).data('id');
            client_id_sequence.push(id);
          });
          $('#delivery-history-edit-form [name=client_id_sequence]').val(
            JSON.stringify(client_id_sequence)
          );
        });
      });
    </script>
{% endblock %}
