<html>

<head>
  <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <script src="{{ url_for("static", filename="js/d3.min.js") }}"></script>
<style>
rect{
  width: 40px;
  height: 40px;
  stroke: black;
  fill: yellow;
}
svg{
  width:100%;
  height:100%;

}
.bg{
  fill: blue;

}

</style>
</head>
<body>

<script>
console.log("hello");
// d3.json("/api/books").then(function(data){
//   console.log("loaded");
//   console.log(data)
//   var g = d3.select('body')
//   .append('div')
//   .append('div');
//   g.selectAll("div.item")
//   .data(data.books)
//   .enter()
//   .append("div")
//   .attr("class", "item")
//   .text(function(d){return d.title})
//   .style("position", "absolute")
//   .style("top", function (d) { return d.scapeY})
//   .style("left", function (d) { return d.scapeX})
//
// }) //.err(function(err) {console.log("error!", err)})
d3.json("/api/books").then(function(data){
  console.log("loaded");
  console.log(data)

  var svg = d3.select('body')
  .append('svg');

  var bounds = svg.node().getBoundingClientRect(),
    width = bounds.width, height = bounds.height;
  var bg = svg.append("rect")
    .attr("class", "bg")
    .attr("width", width)
    .attr("height", height)
    .style("pointer-events", "all")
    .call(d3.zoom()
            .scaleExtent([1/2, 4])
          .on("zoom", zoomed));

  function zoomed(){
g.attr("transform", d3.event.transform);

  }

  var g = svg.append('g');
  var join = g.selectAll("g.item")
  .data(data.books, function (d) { return d.id });

  // process new items (enter)
  join.enter()
  .append("g")
  .attr("class", "item")
//  .text(function(d){return d.title})
  .style("position", "absolute")
  .attr("transform", function (d) { return "translate("+d.scapeX+","+d.scapeY+")"})
  .append("a")
  .call(d3.drag()
    .container(function(){return this.parentNode})
    .on("start", function(){})
    .on("drag", function(d){
      console.log("dragging", this, d3.event);
      d3.select(this).attr("transform", "translate("+d3.event.x+"," +d3.event.y+")" )
    })
  )
  .attr("xlink:href", function(d){return "/books/"+d.id})
  .append("rect")
  .attr("width", "40")
  .attr("height", "40");
  // update existing elements
  join.transition(1000).attr("transform", function (d) { return "translate("+d.scapeX+","+d.scapeY+")"});
  join.exit().remove();



})

</script>
</body>
</html>
