//Reference: https://codepen.io/eikishi01/pen/yjWOqa
price_per_night = [216, 285, 228, 380, 424, 236, 133, 235, 128, 585, 246, 174, 225, 126, 119, 313];
height_define = [450, 695, 846, 943, 1010, 1070, 1123, 1169, 1205, 1235, 1264, 1291, 1315, 1336, 1356, 1373];
area_define = ['Sydney', 'Waverley', 'Randwick', 'Manly', 'Woollahra', 'North Sydney',
  'Marrickville', 'Leichhardt', 'Botany Bay', 'Mosman', 'Willoughby', 'Canada Bay', 'Lane Cove',
  'Ashfield', 'Burwood', 'Hunters Hill'];

let colors = ["#E7C090", "#ABA8A8", "#C69784", "#ABB19A", "#B49F96", "#D1C3A6", "#A89CAB",
  "#C9D7CB", "#C9CA9C", "#AB987F", "#C6B6D2", "#BDBBB9", "#BCC1D0", "#E3C2B4", "#B79EB2", "#979882"]

var poll = {
  'Entire Homes/ Apartments': {
    Sydney: 3245,
    Waverley: 2000,
    Randwick: 1076,
    Manly: 881,
    Woollahra: 590,
    'North Sydney': 574,
    Marrickville: 381,
    Leichhardt: 376,
    'Botany Bay': 138,
    Mosman: 249,
    Willoughby: 204,
    'Canada Bay': 147,
    'Lane Cove': 103,
    Ashfield: 101,
    Burwood: 88,
    'Hunters Hill': 26
  },

  'Private Rooms': {
    Ashfield: 67,
    'Botany Bay': 230,
    Burwood: 99,
    'Canada Bay': 115,
    'Hunters Hill': 9,
    'Lane Cove': 58,
    Leichhardt: 126,
    Manly: 161,
    Marrickville: 246,
    Mosman: 31,
    'North Sydney': 185,
    Randwick: 665,
    Sydney: 1391,
    Waverley: 737,
    Willoughby: 106,
    Woollahra: 227
  },
  'Shared Rooms': {
    Ashfield: 6,
    'Botany Bay': 6,
    Burwood: 8,
    'Canada Bay': 2,
    'Hunters Hill': 1,
    'Lane Cove': 3,
    Leichhardt: 0,
    Manly: 2,
    Marrickville: 5,
    Mosman: 0,
    'North Sydney': 4,
    Randwick: 21,
    Sydney: 118,
    Waverley: 37,
    Willoughby: 4,
    Woollahra: 5
  },
  'Hotel Rooms': {
    Ashfield: 0,
    'Botany Bay': 1,
    Burwood: 0,
    'Canada Bay': 0,
    'Hunters Hill': 0,
    'Lane Cove': 0,
    Leichhardt: 0,
    Manly: 2,
    Marrickville: 3,
    Mosman: 0,
    'North Sydney': 2,
    Randwick: 23,
    Sydney: 57,
    Waverley: 4,
    Willoughby: 0,
    Woollahra: 0
  },

};

var colours = {
  //1
  "Sydney_area": "#E7C090",
  //2
  "Waverley_area": "#ABA8A8",
  //3
  "Randwick_area": "#C69784",
  //4
  "Manly_area": "#ABB19A",
  //5
  "Woollahra_area": "#B49F96",
  //6
  "North Sydney_area": "#D1C3A6",
  //7
  "Marrickville_area": "#A89CAB",
  //8
  "Leichhardt_area": "#C9D7CB",
  //9
  "Botany Bay_area": "#C9CA9C",
  //10
  "Mosman_area": "#AB987F",
  //11
  "Willoughby_area": "#C6B6D2",
  //12
  "Canada Bay_area": "#BDBBB9",
  //13
  "Lane Cove_area": "#BCC1D0",
  //14
  "Ashfield_area": "#E3C2B4",
  //15
  "Burwood_area": "#B79EB2",
  //16
  "Hunters Hill_area": "#979882",

  //Room Types
  "Entire Homes/ Apartments_type": "#8dd3c7",
  "Private Rooms_type": "#EEA45B",
  "Shared Rooms_type": "#bebada",
  "Hotel Rooms_type": "#fb8072"
}

// const width = 1000;
// const height = 1200;
// const = innerWidth = width - margin.left - margin.right,
// const = innerHeight = height - margin.top - margin.bottom;
///////////Design///////////


var svg = d3.select("#sankeyChart"),
  margin = { top: 300, right: -120, bottom: 20, left: 550 },//ori-bottom-(-20)
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom;

// const width = 1000;
// const height = 1200;
// let margin = { top: 200, right: -100, bottom: -500, left: 0 };
// const innerWidth = width - margin.left;
// const innerHeight = height - margin.top - margin.bottom;

var g = svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var formatNumber = d3.format(",.0f"),
  color = d3.scaleOrdinal(d3.schemeSet3);

const sankey = d3.sankey()
  .nodeWidth(10) // each rectangle in the sankey chart
  .nodePadding(10)
  .iterations(0)
  // .nodeAlign(d3[`sankey${align[0].toUpperCase()}${align.slice(1)}`])
  // .nodeSort(null)
  // .nodeSort(inputOrder ? null : undefined)
  .extent([[1, 1], [width - 1, height - 6]]);
/* 
If extent is specified, sets the extent of the Sankey layout
 to the specified bounds and returns the layout. The extent bounds
  are specified as an array [[x0, y0], [x1, y1]], where x0 is the 
  left side of the extent, y0 is the top, x1 is the right and y1 
  is the bottom. If extent is not specified, returns the current 
  extent which defaults to [[0, 0], [1, 1]].
*/

//link
var link = g.append("g")
  .attr("class", "links")
  .attr("fill", "none")
  .attr("stroke", "#000")
  .attr("stroke-opacity", 0.5)
  .selectAll("path")
  .sort(function (a, b) {
    return b.dy - a.dy;
  });
//node
var node = g.append("g")
  .attr("class", "nodes")
  .attr("font-family", "sans-serif")
  .attr("font-size", 10)
  .selectAll("g");

var indexLookup = {};

var pollNodes = {
  "nodes": [],
  "links": []
};

create(null, poll);

function create(error, poll) {
  if (error) throw error;

  // first convert the data into a suitable format for generating a sankey diagram

  // generate area nodes
  for (var roomType_right in poll) {
    if (roomType_right == "Entire Homes/ Apartments") {
      for (var sydneyArea_left in poll[roomType_right]) {
        pollNodes["nodes"].push({
          "name": sydneyArea_left + "_area"
        });
        var currentSize = pollNodes["nodes"].length - 1;
        indexLookup[sydneyArea_left + "_area"] = currentSize;

      }
    }
    // generate type nodes
    pollNodes["nodes"].push({
      "name": roomType_right + "_type"
    });
    var currentSize = pollNodes["nodes"].length - 1;
    indexLookup[roomType_right + "_type"] = currentSize;
  }

  var total = 0;

  for (var roomType_right in poll) {
    for (var sydneyArea_left in poll[roomType_right]) {
      if (poll[roomType_right][sydneyArea_left] !== 0) {
        pollNodes["links"].push({
          "source": indexLookup[sydneyArea_left + "_area"],
          "target": indexLookup[roomType_right + "_type"],
          "room": roomType_right + "_type",
          "area": sydneyArea_left + "_area",
          "value": poll[roomType_right][sydneyArea_left]
        });
        total += poll[roomType_right][sydneyArea_left];
      }
    }
  }

  // generate sankey layout
  sankey(pollNodes);

  link = link
    .data(pollNodes.links)
    .enter().append("path")
    .attr("d", d3.sankeyLinkHorizontal())
    //Width of links
    .attr("stroke-width", function (d) {
      return Math.max(1, d.dy);
    })

    //Color of links
    .attr("stroke", function (d) {
      return colours[d.source.name];
    })
    //Change the opacity when moussover
    .on("mouseover", function () {
      d3.select(this)
        .attr("stroke-opacity", 0.7);
    })
    //Change to original opacity when momuseout
    .on("mouseout", function () {
      d3.select(this)
        .attr("stroke-opacity", 0.35);
    })

  //For links: present the value when mouseOver
  link.append("title")
    .text(function (d) { return d.room.slice(0, -5) + " in " + d.area.slice(0, -5) + ":" + "\n" + d.value; });

  node = node
    .data(pollNodes.nodes)
    .enter().append("g")
    .attr("transform", function (d) { console.log("Value of d.y: " + d.y); return "translate(" + d.x + "," + d.y + ")"; });


  node.append("rect")

    .attr("height", function (d) { return d.dy; })
    .attr("width", sankey.nodeWidth())
    .attr("fill", function (d) {
      return colours[d.name] || "#D3D3D3";
    })
    //Add border to the node
    // .attr("stroke", "white")
    // .attr("stroke-width", 2)
    .append("title")
    .text(function (d) { return "Total listings in " + d.name.slice(0, -5) + ":" + "\n" + d.value; })


  node.append("text")
    .attr("x", sankey.nodeWidth() + 10)
    .attr("y", function (d) { return d.dy / 2; })
    .attr("dy", "0.35em")
    .attr("text-anchor", "start")
    .attr("transform", null)
    // .attr("fill", '#000000')
    // .attr("style", 'fill:#000000')
    //Transfer to percentage
    .text(function (d) { return d.name.slice(0, -5) + ": " + Math.round(d.value / total * 100) + "%"; })
    .filter(function (d) { return d.x < width / 2; })
    .attr("x", sankey.nodeWidth() - 25)
    .attr("text-anchor", "end");



  //Append proportional area chart
  for (i = 0; i < price_per_night.length; i++) {
    svg.append('circle')
      .data(pollNodes.nodes)
      .attr('cx', width * 0.75 - (price_per_night[i] * 0.63))
      .attr('cy', height_define[i])
      // .attr('r', price_per_night[i] * 0.1)
      .attr('r', 8)
      // .attr('cy', function (d) { console.log("Value of d.y: " + d.y); return "translate(" + (100 + d.x) + "," + d.y + ")"; })
      .attr('stroke', '#6F7381')
      .attr('stroke-width', 1)
      .attr('fill', colors[i])
      .attr('fill-opacity', 0.6)
      .append("title")
      .text(function (d) { return "The average price per night in " + area_define[i] + ":" + "\n" + "$" + price_per_night[i] + "/night"; })

    svg.append('text')
      .data(pollNodes.nodes)
      .attr('x', width * 0.744 - (price_per_night[i] * 0.63))
      .attr('y', 4 + height_define[i])
      .attr("font-size", "12px")
      .attr("fill", '#484A4F')
      // .attr("font", "sans-serif")
      .text("$")

    svg.append('text')
      .data(pollNodes.nodes)
      .attr('x', width * 0.67 - (price_per_night[i] * 0.63))
      .attr('y', 5 + height_define[i])
      .attr("font-size", "13px")
      .attr("fill", '#484A4F')
      // .attr("font", "sans-serif")
      .text(function (d) { return price_per_night[i] })

    svg.append('line')
      // .attr('x1', width * 0.12)
      .attr('x1', width * 0.75 - (price_per_night[i] * 0.63))
      .attr('y1', height_define[i])
      .attr('x2', width * 0.75)
      .attr('y2', height_define[i])
      .attr('stroke', colors[i])
      .attr('stroke-width', 3)
      .attr('stroke-dasharray', '4')
      .style('opacity', 0.6)
  }





  ////////////////////////////////////////
  //price per night
  svg.append('rect')
    .attr('x', width * 0.01)
    .attr('y', height * 0.14)
    .attr('height', 70)
    .attr('width', 180)
    .attr('fill', 'none')
    .attr('stroke-width', 1)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('rect')
    .attr('x', width * 0.028)
    .attr('y', height * 0.15)
    .attr('height', 50)
    .attr('width', 160)
    .attr('fill', 'none')
    .attr('stroke-width', 0.5)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('text')
    .attr("x", width * 0.078)
    .attr("y", height * 0.18)
    .attr("fill", '#484A4F')
    .attr("font-size", "18px")
    .attr("font", "sans-serif")
    .text("Price/night")

  //total listings
  svg.append('rect')
    .attr('x', width * 0.85)
    .attr('y', height * 0.14)
    .attr('height', 70)
    .attr('width', 180)
    .attr('fill', 'none')
    .attr('stroke-width', 1)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('rect')
    .attr('x', width * 0.868)
    .attr('y', height * 0.15)
    .attr('height', 50)
    .attr('width', 160)
    .attr('fill', 'none')
    .attr('stroke-width', 0.5)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('text')
    .attr("x", width * 0.91)
    .attr("y", height * 0.18)
    .attr("fill", '#484A4F')
    .attr("font-size", "18px")
    .attr("font", "sans-serif")
    .text("Total listings")

  //room type
  svg.append('rect')
    .attr('x', width * 1.8)
    .attr('y', height * 0.14)
    .attr('height', 70)
    .attr('width', 180)
    .attr('fill', 'none')
    .attr('stroke-width', 1)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('rect')
    .attr('x', width * 1.818)
    .attr('y', height * 0.15)
    .attr('height', 50)
    .attr('width', 160)
    .attr('fill', 'none')
    .attr('stroke-width', 0.5)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('text')
    .attr("x", width * 1.86)
    .attr("y", height * 0.18)
    .attr("fill", '#484A4F')
    .attr("font-size", "18px")
    .attr("font", "sans-serif")
    .text("Room types")


  //title
  svg.append('rect')
    .attr('x', width * 0.47)
    .attr('y', height * 0.01)
    .attr('height', 70)
    .attr('width', 720)
    .attr('fill', 'none')
    .attr('stroke-width', 1)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('rect')
    .attr('x', width * 0.488)
    .attr('y', height * 0.019)
    .attr('height', 50)
    .attr('width', 700)
    .attr('fill', 'none')
    .attr('stroke-width', 0.5)
    .attr('stroke', '#484A4F')
    .attr('margin', '0')
  svg.append('text')
    .attr("x", width * 0.55)
    .attr("y", height * 0.05)
    .attr("fill", '#484A4F')
    .attr("font-size", "18px")
    .attr("font", "sans-serif")
    .text("What are the nightly price and popular room types in 16 Sydney areas?")
}
