{% extends "layers/layer_base.html" %}
{% load i18n %}
{% load dialogos_tags %}
{% load agon_ratings_tags %}
{% load bootstrap_tags %}
{% load pagination_tags %}
{% load url from future %}
{% load base_tags %}
{% load guardian_tags %}

{% block title %}{{ resource.title|default:resource.alternate }} — {{ block.super }}{% endblock %}

{% block head %}

  {% if TWITTER_CARD %}
    {% include "base/_resourcebase_twittercard.html" %}
  {% endif %}

  {% if OPENGRAPH_ENABLED %}
    {% include "base/_resourcebase_opengraph.html" %}
  {% endif %}

  {% if preview == 'geoext' %}
    {% include "layers/layer_geoext_map.html" %}
  {% elif preview == 'OL3' %}
    {% include "layers/layer_ol3_map.html" %}
  {% elif preview == 'react' %}
		{% include 'geonode-client/layer_map.html' %}
  {% else %}
    {% include "layers/layer_leaflet_map.html" %}
  {% endif %}
{{ block.super }}
{% endblock %}


{% block body_class %}layers{% endblock %}

{% block body_outer %}
<div class="page-header">
  <h2 class="page-title">{{ resource.title|default:resource.alternate }}</h2>
</div>

<div class="row">
  <div class="col-md-8">

    <div id="embedded_map" class="mrg-btm">
      <div id="preview_map"></div>
    </div>

    <div class="layer-actions">
      {% include "_actions.html" %}
    </div>

    <div class="tab-content">
      <article id="info" class="tab-pane{% if tab == 'info' or not tab %} active{% endif %}">
        {% include "base/resourcebase_info_panel.html" %}
      </article>

      {% if resource.is_mosaic %}
      <article id="granules" class="description tab-pane {% if tab and tab == 'granules' %}active{% endif %}">
        <div class="paginate-contents">

            <form method="GET" action="{% url "layer_detail" resource.layer.service_typename %}">
                {% csrf_token %}
                <input type="text" id="filter" name="filter" style="witdh:400px"/>&nbsp;<input type="submit" value='{% trans "Filter Granules" %}'/>
                </br>
                {% if filter %}
                <strong>{% trans "Active Filter:" %}</strong> <em>{{ filter }}</em>
                {% endif %}
            </form>
            <table class="table table-striped table-bordered table-condensed">
              <thead>
                <tr>
                  <!-- th>{% trans "Granule ID" %}</th -->
                  <th>{% trans "Bounding Box" %} (minX,minY,maxX,maxY)</th>
                  <th>{% trans "Time" %}</th>
                  <!-- th>{% trans "Elevation" %}</th -->
                  <th>{% trans "Actions" %}</th>
                </tr>
              </thead>
              <tbody>
                {% autopaginate all_granules.features 10 %}
                {% for feature in granules.features %}
                  <tr>
                    <!-- td>{{ feature.id }}</td -->
                    <td><script language="Javascript">var bbox = JSON.parse('{{ feature.geometry.coordinates }}'); document.write('{{ granules.crs.properties.name }};' + bbox[0][0][0] + ',' + bbox[0][0][1] + ',' + bbox[0][2][0] + ',' + bbox[0][2][1]);</script></td>
                    <td>{% if feature.properties.time %}{{ feature.properties.time }}{% endif %}</td>
                    <!-- td>{% if feature.properties.elevation %}{{ feature.properties.elevation }}{% endif %}</td -->
                    <td>
                        <a class="btn btn-xs" href="#" onclick="doPreview('{{ resource.service_typename }}', '{{ feature.id }}', '{{ granules.crs.properties.name }}', '{{ feature.geometry.coordinates }}', {% if feature.properties.time %}'{{ feature.properties.time }}'{% else %}null{% endif %});"><img alt="Granule Preview" title="Granule Preview" src="/static/lib/img/map_go.png"/></a>
                        <a class="btn btn-xs" href="{% url "layer_granule_remove" feature.id resource.service_typename %}"><img alt="Granule Remove" title="Granule Remove" src="/static/lib/img/cancel-on.png"/></a>
                        <script language="Javascript">
                            function doPreview(layer_name, feature_id, srs, the_geom, time) {
                                var map = app.mapPanel.map;
                                for (var ll = 0; ll < app.map.layers.length; ll++) {
                                    var layer = app.map.layers[ll];
                                    if (layer.name == layer_name) {
                                        if (time) {
                                            var re = new RegExp("(\\+[0-9]{4})", "gm");
                                            var timePosition = time;
                                            if (re.test(time)) timePosition = time.replace(re, 'Z');
                                            map.layers[ll].mergeNewParams({"TIME" : timePosition, "CQL_FILTER" : "IN ('" + feature_id + "')"});
                                        }
                                        else {
                                            map.layers[ll].mergeNewParams({"CQL_FILTER" : "IN ('" + feature_id + "')"});
                                        }

                                        map.layers[ll].addOptions({
                                            singleTile: true
                                        });

                                        bbox = JSON.parse(the_geom);
                                        bbox = new OpenLayers.Bounds(bbox[0][0][0],bbox[0][0][1],bbox[0][2][0],bbox[0][2][1]).transform(srs, map.projection);

                                        //map.maxExtent = bbox;
                                        //map.restrictedExtent = bbox;
                                        map.maxExtent = new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34);
                                        map.restrictedExtent = map.maxExtent;

                                        map.zoomToExtent(bbox);
                                    }
                                }
                            }
                        </script>
                    </td>
                  </tr>
                {% endfor %}
              </tbody>
            </table>
        </div>
        {% paginate %}
      </article>
     {% endif %}

      <article id="attributes" class="tab-pane">
        {% if resource.is_mosaic %}
            <table class="table table-striped table-bordered table-condensed">
              <thead>
                <tr>
                  <th>{% trans "Dimension" %}</th>
                  <th>{% trans "Enabled" %}</th>
                  <th>{% trans "Regex" %}</th>
                </tr>
              </thead>
              <tbody>
                  <tr>
                    <td title="TIME">{% trans "TIME" %}</td>
                    <td>{% if resource.has_time %}{% trans "True" %}{% else %}{% trans "False" %}{% endif %}</td>
                    <td>{% if resource.time_regex %}{{ resource.time_regex }}{% else %}&nbsp;{% endif %}</td>
                  </tr>
                  <!-- tr>
                    <td title="ELEVATION">{% trans "ELEVATION" %}</td>
                    <td>{% if resource.has_elevation %}{% trans "True" %}{% else %}{% trans "False" %}{% endif %}</td>
                    <td>{% if resource.elevation_regex %}{{ resource.elevation_regex }}{% else %}&nbsp;{% endif %}</td>
                  </tr -->
              </tbody>
            </table>
        {% endif %}
        {% if resource.attribute_set.all %}
            <table class="table table-striped table-bordered table-condensed">
              <thead>
                <tr>
                  <th>{% trans "Attribute Name" %}</th>
                  <th>{% trans "Label" %}</th>
                  <th>{% trans "Description" %}</th>
                  {% if wps_enabled %}
                    <th>{% trans "Range" %}</th>
                    <th>{% trans "Average" %}</th>
                    <th>{% trans "Median" %}</th>
                    <th>{% trans "Standard Deviation" %}</th>
                  {% endif %}
                </tr>
              </thead>
              <tbody>
                {% for attribute in resource.attributes %}
                  <tr>
                    <td>{{ attribute.attribute }}</td>
                    <td>{{ attribute.attribute_label|default:"" }}</td>
                    <td>{{ attribute.description|default:"" }}</td>
                    {% if wps_enabled %}
                      {% if attribute.unique_values == "NA" %}
                      <td>{{ attribute.unique_values }}</td>
                      {% else %}
                      <td>
                        <select name="unique_values">
                        {% for value in attribute.unique_values_as_list %}
                          <option value="{{ value }}">{{ value }}</option>
                        {% endfor %}
                        </select>
                      </td>
                      {% endif %}
                      <td>{{ attribute.average|floatformat:"2" }}</td>
                      <td>{{ attribute.median|floatformat:"2" }}</td>
                      <td>{{ attribute.stddev|floatformat:"2" }}</td>
                    {% endif %}
                  </tr>
                {% endfor %}
              </tbody>
            </table>
        {% endif %}
      </article>

      {% block social_links %}
      {% if DISPLAY_SOCIAL %}
        {% include "social_links.html" %}
      {% endif %}
      {% endblock %}

      {% if DISPLAY_COMMENTS %}
      <article id="comments" class="tab-pane">
        {% with resource as obj %}
          {% include "_comments.html" %}
        {% endwith %}
      </article>
      {% endif %}

      {% if GEOGIG_ENABLED and resource.link_set.geogig %}
        {% with "_geogig_layer_detail.html" as geogig_template %}
        <article id="geogig" class="tab-pane">
          {% with resource as obj %}
            {% include geogig_template %}
          {% endwith %}
        </article>
        {% endwith %}
      {% endif %}

      {% if DISPLAY_RATINGS %}
      <article id="rate" class="tab-pane">
        <!-- TODO: Move this to a reusable template snippet -->
        {% if request.user.is_authenticated %}
        <h4>{% trans "Rate this layer" %}</h4>
        {% user_rating request.user resource "layer" as user_layer_rating %}
        <div id="user_rating" class="category-layer" data-score="{{ user_layer_rating }}"></div>
        {% endif %}
        <h4>{% trans 'Average Rating' %}</h4>
        {% overall_rating resource "layer" as layer_rating %}
        {% num_ratings resource as num_votes %}
        <div class="overall_rating" data-score="{{ layer_rating }}"></div> ({{num_votes}})
      </article>
      {% endif %}

    </div>

  </div>

  <div class="col-md-4">

    <ul class="list-group">
      {% if resource.storeType != "remoteStore" %}
        <li class="list-group-item">
        {% if links or links_download %}
           <button class="btn btn-primary btn-md btn-block" data-toggle="modal" data-target="#download-layer">{% trans "Download Layer" %}</button>
        {% else %}
          {% if request.user.is_authenticated %}
          <button class="btn btn-primary btn-md btn-block" id="request-download">{% trans "Request Download" %}</button>
          {% endif %}
        {% endif %}
        </li>
      {% endif %}
    <div class="modal fade" id="download-layer" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">{% trans "Download Layer" %}</h4>
          </div>
          <div class="modal-body">
            <div class="tabbable">
                <ul class="nav nav-tabs">
                    {% if links %}
                    <li class="active"><a href="#download_tab1" data-toggle="tab">Images</a></li>
                    {% endif %}
                    {% if links_download %}
                    <li><a href="#download_tab2" data-toggle="tab">Data</a></li>
                    {% endif %}
                </ul>
                <div class="tab-content">
                {% if links %}
                    <div class="tab-pane active" id="download_tab1">
                        <li class="active">
                            <ul>
                              {% for link in links %}
                              <li><a href="{{ link.url }}" target="_blank">{% trans link.name %}</a></li>
                              {% endfor %}
                            </ul>
                        </li>
                    </div>
                {% endif %}
                {% if links_download %}
                    <div class="tab-pane" id="download_tab2">
                        <li>
                            <ul>
                              {% for link in links_download %}
                              <li><a href="{{ link.url }}" target="_blank">{% trans link.name %}</a></li>
                              {% endfor %}
                            </ul>
                        </li>
                    </div>
                {% endif %}
                </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
          </div>
        </div>
      </div>
    </div>

    {% if GEOSERVER_BASE_URL %}
      {% get_obj_perms request.user for resource.layer as "layer_perms" %}
    {% endif %}

    <li class="list-group-item">
      <a href="{% url "layer_metadata_detail" resource.alternate %}">
        <button class="btn btn-primary btn-md btn-block">{% trans "Metadata Detail" %}</button>
      </a>
    </li>

    {% if "change_resourcebase_metadata" in perms_list or "change_resourcebase" in perms_list or "delete_resourcebase" in perms_list or "change_layer_style" in layer_perms %}
    <li class="list-group-item">
      <button class="btn btn-primary btn-md btn-block" data-toggle="modal" data-target="#edit-layer">{% trans "Edit Layer" %}</button>
    </li>
    <div class="modal fade" id="edit-layer" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">{% trans "Edit Layer" %}</h4>
          </div>
          <div class="modal-body">
            <div class="row edit-modal">
              {% if "change_resourcebase_metadata" in perms_list %}
              <div class="col-sm-3">
                <i class="fa fa-list-alt fa-3x"></i>
                <h4>{% trans "Metadata" %}</h4>
                <a class="btn btn-default btn-block btn-xs" href="{% url "layer_metadata" resource.service_typename %}">{% trans "Wizard" %}</a>
                <a class="btn btn-default btn-block btn-xs" href="{% url "layer_metadata_advanced" resource.service_typename %}">{% trans "Advanced Edit" %}</a>
                <a class="btn btn-default btn-block btn-xs" href="{% url "layer_metadata_upload" resource.service_typename %}">{% trans "Upload Metadata" %}</a>
              </div>
              {% endif %}
              {% if GEOSERVER_BASE_URL and not resource.service %}
                {% if "change_layer_style" in layer_perms %}
                <div class="col-sm-3">
                  <i class="fa fa-tint fa-3x"></i>
                  <h4>{% trans "Styles" %}</h4>
                  {% if preview == 'geoext' %}
                  <a class="btn btn-default btn-block btn-xs style-edit" data-dismiss="modal" href="#">{% trans "Edit" %}</a>
                  {% endif %}
                  <a class="btn btn-default btn-block btn-xs" href="{% url "layer_style_manage" resource.service_typename %}">{% trans "Manage" %}</a>
                </div>
                {% endif %}
              {% endif %}
              {% if "change_resourcebase" in perms_list %}
              <div class="col-sm-3">
                <i class="fa fa-photo fa-3x"></i>
                <h4>{% trans "Thumbnail" %}</h4>
                <a class="btn btn-default btn-block btn-xs" href="#" id="set_thumbnail">{% trans "Set" %}</a>
              </div>
              {% endif %}
              {% if "change_resourcebase" in perms_list or "delete_resourcebase" in perms_list or "change_layer_data" in layer_perms %}
              <div class="col-sm-3">
                <i class="fa fa-square-o fa-3x rotate-45"></i>
                <h4>{% trans "Layer" %}</h4>
                {% if "change_resourcebase" in perms_list and not resource.service %}
                <a class="btn btn-default btn-block btn-xs" href="{% url "layer_replace" resource.service_typename %}">{% trans "Replace" %}</a>
                {% endif %}
                {% if resource.storeType == 'dataStore' and "change_layer_data" in layer_perms %}
                <a class="btn btn-default btn-block btn-xs" href="{% url "new_map" %}?layer={{resource.service_typename}}">{% trans "Edit data" %}</a>
                {% endif %}
                {% if "delete_resourcebase" in perms_list %}
                <a class="btn btn-danger btn-block btn-xs" href="{% url "layer_remove" resource.service_typename %}">{% trans "Remove" %}</a>
                {% endif %}
              </div>
              {% endif %}
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
          </div>
        </div>
      </div>
    </div>
    {% endif %}

    <li class="list-group-item">
      <button class="btn btn-default btn-md btn-block" data-toggle="modal" data-target="#download-metadata">{% trans "Download Metadata" %}</button>
    </li>

    <div class="modal fade" id="download-metadata" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">{% trans "Download Metadata" %}</h4>
          </div>
          <div class="modal-body">
		    <div style="margin-bottom:20px">
				 <h5 class="modal-title" id="myModalLabel">
				Full metadata
				 </h5>
                 <ul>
 					<li><a target="_blank" href="../catalogue/csw_to_extra_format/{{resource.uuid}}/{{resource.title}}.txt"> Text format </a></li>
 					<li><a target="_blank" href="../catalogue/csw_to_extra_format/{{resource.uuid}}/{{resource.title}}.html"> HTML format </a></li>
 				</ul>
			</div>
		    <div style="margin-bottom:20px">
			<h5 class="modal-title" id="myModalLabel">
			Standard Metadata - XML format
			</h5>
            <ul>
              {% for link in metadata %}
                <li><a href="{{ link.url }}" target="_blank">{{ link.name }}</a></li>
              {% endfor %}
            <ul>
            </div>
            {% if resource.storeType == 'dataStore' %}
            <h5 class="modal-title" id="myModalLabel">Attribute Information</h5>
            <ul>
              <li><a href="{{ resource.get_absolute_url }}/feature_catalogue" target="_blank">ISO Feature Catalogue</a></li>
            <ul>
            {% endif %}
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
          </div>
        </div>
      </div>
    </div>

    {% if resource.get_legend %}
    <li class="list-group-item">
      <h4 class="list-group-item-heading">{%trans "Legend" %}</h4>
      <p>{{ style.sld_title }}</p>
      {% if resource.get_legend.link_type == 'image' %}
        {% if request.user.is_authenticated and 'access_token' in request.session %}
            <p><img id="legend_icon" src="{{ resource.get_legend.url }}&access_token={{ request.session.access_token }}"></p>
        {% else %}
            <p><img id="legend_icon" src="{{ resource.get_legend.url }}"></p>
        {% endif %}
      {% else %}
      <div id='legend_placeholder'></div>
      {% endif %}
    </li>
    {% endif %}
    <li class="list-group-item">
      <h4>{% trans "Maps using this layer" %}</h4>
      {% if resource.maps %}
        <p>{% trans "List of maps using this layer:" %}</p>
        {% endif %}
        <ul class="list-unstyled">
          {% for maplayer in resource.maps %}
            <li><a href="{{ maplayer.map.get_absolute_url }}">{{ maplayer.map.title }}</a></li>
          {% empty %}
            <li>{% trans "This layer is not currently used in any maps." %}</li>
          {% endfor %}
        </ul>
    </li>
    <li class="list-group-item">
      <h4>{% trans "Create a map using this layer" %}</h4>
      <p>{% trans "Click the button below to generate a new map based on this layer." %}</p>
        <a href="{% url "new_map" %}?layer={{resource.service_typename}}" class="btn btn-primary btn-block">{% trans "Create a Map" %}</a>
    </li>

    {% if documents.count > 0 %}
    <li class="list-group-item">
      <h4>{% trans "Documents related to this layer" %}</h4>
      <p>{% trans "List of documents related to this layer:" %}</p>
      <ul class="list-unstyled">
        {% for document in documents %}
          <li><a href="{{ document.get_absolute_url }}">{{ document.title }}</a></li>
        {% endfor %}
      </ul>
    </li>
    {% endif %}

    {% if user.is_authenticated %}
    <li class="list-group-item">
      <h4>{% trans "Styles" %}</h4>
       <p>{% trans "The following styles are associated with this layer. Choose a style to view it in the preview map." %}</p>
       <ul class="list-unstyled">
        {% for style in resource.styles.all %}
        <li>
          {% if resource.default_style == style %}
          <input type="radio" checked name="style" id="{{ style.name }}" value="{{ style.title }}"/>
          (default style)
          {% else %}
          <input type="radio" name="style" id="{{ style.name }}" value="{{ style.title }}"/>
          {% endif %}
          <a href="{{ GEOSERVER_BASE_URL }}{{ style.absolute_url }}" >{{ style.sld_title }}</a>
        </li>
        {% empty %}
        <li>{% trans "No styles associated with this layer" %}</li>
        {% endfor %}
      </ul>
    </li>
    {% endif %}

    {% if GEONODE_SECURITY_ENABLED %}
    {% if "change_resourcebase_permissions" in perms_list %}
    <li class="list-group-item">
      <h4>{% trans "Permissions" %}</h4>
      <p>{% trans "Click the button below to change the permissions of this layer." %}</p>
      <p><a href="#modal_perms" data-toggle="modal" class="btn btn-primary btn-block" data-target="#_permissions">{% trans "Change Layer Permissions" %}</a></p>
    </li>
    {% endif %}
    {% endif %}

    {% if resource.storeType == "remoteStore" %}
    <li class="list-group-item">
            <h4>{% trans "External service layer" %}</h4>
            <div>{% trans "Source" %}: <a href="/services/{{resource.service.id}}">{{ resource.service.title }}</a></div>
            <div>{% trans "Type" %}: {{ resource.service.type }}</div>
    </li>
    {% endif %}

    {% include "base/_resourcebase_contact_snippet.html" %}
  </ul>


  {% if GEONODE_SECURITY_ENABLED %}
    {% include "_permissions_form.html" %}
  {% endif %}

  </div> <!-- col-md-4 -->
</div> <!-- row -->
{% endblock %}

{% block extra_script %}
{{ block.super }}

    {% if GEOGIG_ENABLED and resource.link_set.geogig %}
        {% with "_geogig_scripts.html" as geogig_scripts_template %}
            {% include  geogig_scripts_template %}
        {% endwith %}
    {% endif %}

    {% if request.user.is_authenticated %}
        {% user_rating_js request.user resource "layer" %}
    {% else %}
      {% overall_rating resource 'layer' as the_layer_rating %}
    {% endif %}
    {% include 'rating.html' %}
    {% include 'request_download.html' %}
    <script type="text/javascript">
       $("#comment_submit_btn").click(function(event) {
            $.ajax({
              type: "POST",
              url: $("#form_post_comment").attr('action'),
              data: $("#form_post_comment").serialize(),
              success: function() {
                $('#form_post_comment_div').modal().find('form')[0].reset();
                $('#form_post_comment_div').modal('hide');
                $('#comments_section').load(window.location.pathname + ' #comments_section',
                		function(){$(this).children().unwrap()})
              }
            });
            return false;
          });

    {% if resource.get_legend.link_type == 'json' %}
    $.getJSON('{{resource.get_legend_url}}', function (data) {
        var legend = data.layers[0].legend;
        var items = [];
        $.each(legend, function (key, dvalue) {
            items.push('<li><img src="data:image/png;base64,' + dvalue.imageData + '">'+dvalue.label+'</li>');
        });

        $('<ul/>', {
            'class': 'arcgis-legend',
            html: items.join('')

        }).appendTo('#legend_placeholder');

    });
    {% endif %}
        </script>
    <script type="text/javascript">
    {% if preview == 'react' %}
    $('#set_thumbnail').click(function(){
      window.setThumbnail({{resource.id}})
      $('#edit-layer').modal('toggle');
    });
    {% else %}
    $('#set_thumbnail').click(function(){
      createMapThumbnail();
      $('#edit-layer').modal('toggle');
    });
    {% endif %}

    </script>
    {% if GEONODE_SECURITY_ENABLED %}
    {% include "_permissions_form_js.html" %}
    {% endif %}
{% endblock extra_script %}
