{% extends 'warp_base.html' %}
{% load staticfiles %}
{% load l10n %}
{% comment %} {% endcomment %}

{% block custom_style_link %}
<link rel="stylesheet" href="{{settings.STATIC_URL}}warp/css/ol.css" />
<link rel="stylesheet" href="http://openlayers.org/en/v3.4.0/resources/layout.css" />
{% endblock %}
{% block custom_style_inline %}

#progress {
    background: transparent url("/static/warp/ajax-loader.gif") no-repeat center;
    float: left;
    display: inline-block;
    width: 32px;
    height: 32px;
}

#printOptions {
    float: left;
    display: inline-block;
}

{% endblock %}
{% block custom_js %}
<script type="text/javascript" src="{{settings.STATIC_URL}}warp/js/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/proj4js/2.2.1/proj4.js"></script>
<script src="http://epsg.io/{{ dataset.epsg }}.js"></script>
<script type="text/javascript">

var MapExtent = {{ target.extent }}
{% localize off %}
var targetExtent = [{{ dataset.extentLeft }}, {{ dataset.extentBottom }}, {{ dataset.extentRight }}, {{ dataset.extentTop }}]; 
// PD [1716014, 5023919, 1737137, 5038662];
{% endlocalize %}

var map_print;
var georef_overlay,wms_base,frame_overlay;
var frameGeometry;

{% if dataset.epsg = 3857 or dataset.epsg = 4326 %}
var targetProjection = 'EPSG:{{ dataset.epsg }}';
{% else %}
var targetProjection = new ol.proj.Projection({
  code: 'EPSG:{{ dataset.epsg }}',
  // The extent is used to determine zoom level 0. Recommended values for a
  // projection's validity extent can be found at http://epsg.io/.
  extent: targetExtent,
  //units: 'm'
});
ol.proj.addProjection(targetProjection);
{% endif %}

var frame_source =  new  ol.source.Vector({projection: targetProjection});

var dims = {
  a3: [420, 297],
  a4: [297, 210]
};

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

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


$(document).ready(function(){
    
    $( "#format" ).change(function() {
          draw_frame();
        });

    $( "#scale" ).change(function() {
          draw_frame();
        });

    console.log('doc ready');
});

window.app = {};
var app = window.app;

app.Drag = function() {
  
  ol.interaction.Pointer.call(this, {
    handleDownEvent: app.Drag.prototype.handleDownEvent,
    handleDragEvent: app.Drag.prototype.handleDragEvent,
    handleMoveEvent: app.Drag.prototype.handleMoveEvent,
    handleUpEvent: app.Drag.prototype.handleUpEvent
  });

  this.coordinate_ = null;
  this.cursor_ = 'pointer';
  this.feature_ = null;
  this.previousCursor_ = undefined;

};

ol.inherits(app.Drag, ol.interaction.Pointer);

app.Drag.prototype.handleDownEvent = function(evt) {
  var map = evt.map;

  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      }, 
      null, 
      function(layer) {
        return layer === frame_overlay;
      });

  if (feature) {
    this.coordinate_ = evt.coordinate;
    this.feature_ = feature;
  }

  return !!feature;
};

app.Drag.prototype.handleDragEvent = function(evt) {
  var map = evt.map;
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      }, 
      null, 
      function(layer) {
        return layer === frame_overlay;
      });
  var deltaX = evt.coordinate[0] - this.coordinate_[0];
  var deltaY = evt.coordinate[1] - this.coordinate_[1];
  var geometry = /** @type {ol.geom.SimpleGeometry} */
      (this.feature_.getGeometry());
  geometry.translate(deltaX, deltaY);
  this.coordinate_[0] = evt.coordinate[0];
  this.coordinate_[1] = evt.coordinate[1];
};

app.Drag.prototype.handleMoveEvent = function(evt) {
  if (this.cursor_) {
    var map = evt.map;
    var feature = map.forEachFeatureAtPixel(evt.pixel,
        function(feature, layer) {
          return feature;
      }, 
      null, 
      function(layer) {
        return layer === frame_overlay;
        });
    var element = evt.map.getTargetElement();
    if (feature) {
      if (element.style.cursor != this.cursor_) {
        this.previousCursor_ = element.style.cursor;
        element.style.cursor = this.cursor_;
      }
    } else if (this.previousCursor_ !== undefined) {
      element.style.cursor = this.previousCursor_;
      this.previousCursor_ = undefined;
    }
  }
};

app.Drag.prototype.handleUpEvent = function(evt) {
  this.coordinate_ = null;
  this.feature_ = null;
  return false;
};

var drag_polygon = new app.Drag();

function draw_frame(){

    frame_overlay.setVisible(true);
    var format = document.getElementById('format').value;
    var dim = dims[format];

    var scale = document.getElementById('scale').value;
    var half_scaled_width = dim[0]/1000 * scale/2;
    var half_scaled_height = dim[1]/1000 * scale/2;

    var center = map_print.getView().getCenter();
    var frameExtent = [center[0]-half_scaled_width,center[1]-half_scaled_height,center[0]+half_scaled_width,center[1]+half_scaled_height];
    var framePolygon = [[center[0]-half_scaled_width,center[1]-half_scaled_height],
                       [center[0]-half_scaled_width,center[1]+half_scaled_height],
                       [center[0]+half_scaled_width,center[1]+half_scaled_height],
                       [center[0]+half_scaled_width,center[1]-half_scaled_height]];
    console.log(frameExtent);
    frameGeometry = new ol.geom.Polygon([framePolygon]);
    var frameFeature = new ol.Feature({ geometry : frameGeometry });
    var frameCollection = new ol.Collection([frameFeature]);
    var frame_source = new ol.source.Vector({features: frameCollection});
    frame_overlay.setSource(frame_source);
    return frameExtent;
}

function init(){

    georef_overlay = 
          new ol.layer.Image({
            source: new ol.source.ImageStatic({
              url: '{{target.url}}',
              size: {{target.size}},
              projection: targetProjection,
              imageExtent: MapExtent,
              crossOrigin: null 
            })
          });

    frame_overlay =  new ol.layer.Vector({
      source: frame_source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(51, 153, 255, 0.3)'
        }),
        stroke: new ol.style.Stroke({
          color: '#3399ff',
          width: 3
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#ffcc33'
          })
        })
      })
    })
    
/*
    var wms_base = new ol.layer.Tile({
            extent: targetExtent,
            title: 'PRG',
            source: new ol.source.TileWMS({
              //url: '/warp/proxy/http://localhost/cgi-bin/qgis_mapserv.fcgi?MAP=/usr/lib/cgi-bin/PRG/PRG.qgs',
              url: '/warp/proxy/http://172.25.193.167:8080/service?',
              params: {'LAYERS': 'PRG'}
            })
          });
*/
    var wms_base = new ol.layer.Tile({
        source: new ol.source.OSM()
    });

    map_print = new ol.Map({
      interactions: ol.interaction.defaults().extend([new app.Drag()]),
      layers: [
{{ dataset.baselayer | escape | safe  }}
          georef_overlay,
          frame_overlay
      ],
      controls: ol.control.defaults().extend([
        //new ol.control.ScaleLine({target: 'map_print', 'units': 'metric'}),
        new ol.control.MousePosition(),
        new ol.control.OverviewMap()
      ]),
      target: 'map_print',
      view: new ol.View({
        projection: targetProjection,
        center: ol.extent.getCenter(MapExtent),
        zoom: 2
      })
    });
    
    map_print.getView().fit({{target.extent}}, map_print.getSize());
    
    var exportPNGElement = document.getElementById('esporta_png');

    if ('download' in exportPNGElement) {
      exportPNGElement.addEventListener('click', function(e) {
        map_print.once('postcompose', function(event) {
          var canvas = event.context.canvas;
          exportPNGElement.href = canvas.toDataURL('image/png');
        });
        map_print.renderSync();
      }, false);
    } else {
      var info = document.getElementById('no-download');
      /**
       * display error message
       */
      info.style.display = '';
    }

    var loading = 0;
    var loaded = 0;

    var exportElement = document.getElementById('esporta_pdf');

    exportElement.addEventListener('click', function(e) {
      console.log('START');
      var view_size = map_print.getSize()
      var view_extent = map_print.getView().calculateExtent(view_size)
      if (exportElement.className.indexOf('disabled') > -1) {
        return;
      }
      //exportElement.className += 'disabled';
      $( "#esporta_pdf" ).addClass( 'disabled' );
      $( "#progress" ).removeClass( 'hidden' );

      var format = document.getElementById('format').value;
      var resolution = document.getElementById('resolution').value;
      var dim = dims[format];
      var width = Math.round(dim[0] * resolution / 25.4);
      var height = Math.round(dim[1] * resolution / 25.4);
      var size = [width,height];
      //var size = /** @type {ol.Size} */ (map_print.getSize());
      //var extent = map_print.getView().calculateExtent(size);
      //var extent = draw_frame();
      console.log(draw_frame())
      var extent = frameGeometry.getExtent();
      frame_overlay.setVisible(false);
      console.log(extent)

      console.log('DIM:'+resolution.toString());
      console.log('WID:'+width.toString());
      console.log('HEI:'+height.toString());
      console.log(size);

      var source = wms_base.getSource();

      var tileLoadStart = function() {
        ++loading;
      };

      var tileLoadEnd = function(callback) {
        ++loaded;
        if (loading === loaded) {
          var canvas = this;
          window.setTimeout(function() {
            loading = 0;
            loaded = 0;
            var data = canvas.toDataURL('image/png');
            var pdf = new jsPDF('landscape', undefined, format);
            pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
            pdf.save('map_print.pdf');
            source.un('tileloadstart', tileLoadStart);
            source.un('tileloadend', tileLoadEnd, canvas);
            source.un('tileloaderror', tileLoadEnd, canvas);
            map_print.setSize(view_size);
            map_print.getView().fit(view_extent, view_size,{constrainResolution:false,nearest:true});
            $( "#esporta_pdf" ).removeClass( 'disabled' );
            $( "#progress" ).addClass( 'hidden' );
            frame_overlay.setVisible(true);
            map_print.renderSync();
            document.body.style.cursor = 'auto';
          }, 100);
        }
      };

      map_print.once('postcompose', function(event) {
        source.on('tileloadstart', tileLoadStart);
        source.on('tileloadend', tileLoadEnd, event.context.canvas);
        source.on('tileloaderror', tileLoadEnd, event.context.canvas);
      });

      map_print.setSize(size);
      map_print.getView().fit(extent, size,{constrainResolution:false,nearest:true}); // /** @type {ol.Size} */ (map_print.getSize()));
      map_print.renderSync();
      
      
      console.log('END');

    }, false);

}

</script>
{% endblock %}
{% block onload %} onload="init()"{% endblock %}
{% block titolo %}Print georeferenced image {% if source %}{{source.fileName}}{% endif %}{% endblock %}
{% block menu %}{% endblock %}
{% block contenuto %}


<div class="container"> 
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-body">
            <form id="printOptions" class="form-inline input-sm">
              <div class="form-group">
                  <label for="format">Page size</label>
                  <select id="format" class="form-control">
                    <option value="a3">A3</option>
                    <option value="a4" selected>A4</option>
                  </select>
              </div>
              <div class="form-group">
                  <label>Resolution</label>
                  <select id="resolution" class="form-control">
                    <option value="72">72 dpi (fast)</option>
                    <option value="150">150 dpi</option>
                    <option value="300">300 dpi (slow)</option>
                  </select>
              </div>
              <div class="form-group">
                  <label>Scale 1:</label>
                  <input id="scale" class="form-control" value="2000"></input>
              </div>
            <div class="form-group">
                <a class="btn btn-default" id="esporta_pdf" role="button">Print pdf</a>
                <a class="btn btn-default" id="esporta_png" download="map.png" role="button">Export image</a>
            </div>
            </form>
            </div>
            <div class="pull-right">
                <a id="messaggio_errore"  class="hidden btn btn-warning" role="button">Loading Error</a>
                <div class="hidden" id="progress"></div>
            </div>
            <div class="panel-body">
                <div style="width:100%;height:762px" id="map_print"></div>
            </div>
        </div>
    </div>
  </div>
</div>

{% endblock %}
{% block piedipagina %}{% endblock %}
