//L_PREFER_CANVAS = true;

//window.dash_clientside = Object.assign({}, window.dash_clientside, {
//    clientside: {
//        download_png_frame: function(clicks) {
//          console.log(clicks);
//          var element = document.getElementById("graph-collection"); // global variable
//          var ret = html2canvas(element, {
//              // allowTaint: true,
//              userCORS: true,
//              onrendered: function (canvas) {
//                 var imgData = canvas.toDataURL('image/png');
//                 var downloadData = imgData.replace(/^data:image\/png/, "data:application/octet-stream");
//         return downloadData;
//                 // console.log(downloadData);
//         console.log($("#frame-download"));
//                 $("#frame-download").attr("data", downloadData);     
//                 //window.open(imgData);
//           }
//          } 
//          );
//     return ret;
////          return getCanvas.replace(/^data:image\/png/, "data:application/octet-stream");
////          //var imageData = getCanvas.toDataURL("image/png");
////          // Now browser starts downloading it instead of just showing it
////          return res  // getCanvas.replace(/^data:image\/png/, "data:application/octet-stream");
//        }
//    }
//});


//    $(document).on('click', "#btn-all-frame-download", function () {
//    var models = document.getElementsByClassName("custom-control-input");
//        for (var i=0; i<models.length; i++) {
//      if (models[i].checked == false)
//            models[i].click();
//        }
//        var btn = document.getElementById("models-apply");
//        btn.click();
//        setTimeout (function () {
//            var element = document.getElementById("graph-collection"); // global variable
//            if (element == null) {
//               element = document.getElementById("prob-graph"); // global variable
//               if (element == null) {
//                   element = document.getElementById("was-graph"); // global variable
//               }
//            }
//            getCanvas(element);
//        }, 1700);
//    });
$(document).ready(function () {
    $(document).on('click', "#btn-frame-download", function () {
        var element = document.getElementById("graph-collection"); // global variable
        if (element == null) {
           element = document.getElementById("prob-graph"); // global variable
           if (element == null) {
               element = document.getElementById("was-graph"); // global variable
           }
        }
        getCanvas(element);
    });
});

function calcMarginLeft(item, element){
	elementWidth = element.getBoundingClientRect().width;
	itemWidth = item.getBoundingClientRect().width;
	console.log('Widths : ', elementWidth, itemWidth);
	result = (elementWidth/itemWidth) * 10;
	console.log('Left calc ', result.toString().concat('%'));
	calc = result.toString().concat('%');
	return calc;
}

function calcMarginHeight(item, element){
	elementHeight = element.getBoundingClientRect().height;
	console.log('rect ', item.getBoundingClientRect());
	itemHeight = item.getBoundingClientRect().height;
	console.log('Heights : ', elementHeight, itemHeight);
	result = (elementHeight/itemHeight - .02656) * 10;
	console.log('Top calc ', result.toString().concat('%'));
	calc = result.toString().concat('%');
	return calc; 
}

function pullRandom() {
	const nums = ['-250px', '-30px', '-100px'];
	const random = Math.floor(Math.random() * nums.length);
	return nums[random];
}

function getCanvas(element) {
        html2canvas(element, {
		onclone: (doc) => {
			var items = doc.querySelectorAll('svg');
			for (var j=0; j<items.length; j++) {
				item = items[j];
//				left = item.getBoundingClientRect().left;
//				top1 = item.getBoundingClientRect().top;
//				item.style.left = left.toString().concat('px');
//				item.style.top = top1.toString().concat('px');
				console.log('Item left: ', item.style.left);
				console.log('Item top: ', item.style.top);
				item.style.marginLeft = calcMarginLeft(item, element);
				item.style.marginTop = calcMarginHeight(item, element);
//				default font is set to 16px for html and 12px for leaflet
//				so we must recalculate the rems
				adjustedREMSize = (Math.ceil(3.8*.75)).toString().concat('rem');
				item.style.marginTop = adjustedREMSize;
			}
			},
		  scrollX: 0,
		  scrollY: 0,
          allowTaint: true,
          useCORS: true,
          async: true,
          windowWidth: element.width,
          windowHeight: element.height,
          logging: true,
          imageTimeout: 0,
		  ignoreElements: function( element ) {
			  if( element.classList.contains( 'leaflet-control-zoom' ) || 
				  element.classList.contains( 'leaflet-control-colorbar' ) ||
				  'median-info' == element.id ) {
				return true;
				}
			  },

    }).then(function (canvas) {
            saveAs(canvas.toDataURL(), 'image.png');
    });
}

function saveAs(uri, filename) {
  var link = document.createElement('a');
  if (typeof link.download === 'string') {
    link.href = uri;
    link.download = filename;

    //Firefox requires the link to be in the body
    document.body.appendChild(link);

    //simulate click
    link.click();

    //remove the link when done
    document.body.removeChild(link);
  } else {
    window.open(uri);
  }
}
