<!DOCTYPE html>
<head>
  <meta charset="utf-8">
	<script src='https://d3js.org/d3.v5.min.js'></script>
  <script src="d3-parliament.min.js"></script>
  <style>
    * {
      box-sizing: border-box;
    }
    
    body {
      font-family: "avenir next", Arial, sans-serif;
  		font-size: 12px;
  		margin: 0;
    }
    
    #vis {
			max-width: 550px;
  		margin: 0 auto;
    }
		
    svg .seat.UPA { fill: green; }
    svg .seat.NDA { fill: orange; }
    svg .seat.Other { fill: lightgrey; }
  </style>
</head>

<body>
<div id='vis'></div>

<script>
const margin = {top:80, right:20, left:20, bottom:0};

const $chart = d3.select('#vis');
const width =  parseInt($chart.node().offsetWidth) - margin.left - margin.right;
const height = parseInt(width * 0.7) - margin.top - margin.bottom;

const parliament = d3.parliament()
  .width(width)
  .innerRadiusCoef(0.4);

parliament.enter
  .fromCenter(false)
  .smallToBig(false);

let symbol = d3.symbol().size([50]);

const $svg = d3.select('#vis')
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom)

const $g = $svg.append('g')
  .attr('transform', `translate(${margin.left}, ${margin.top})`)

const $g_annotation = $svg
  .append('g')
  .attr('class', 'annotation')
  .attr('transform', `translate(${margin.left}, 0)`)

function setupChart(data) {
  const parties = data.map(d => {
    let alliance = null;
    if (d.winning_party_alliance === 'National Democratic Alliance') {
      alliance = 'NDA'
    } else if (d.winning_party_alliance === 'United Progressive Alliance') {
      alliance = 'UPA'
    } else {
      alliance = 'Other';
    }
    return {
      ...d,
      alliance: alliance
    }
  })

  const nest = d3.nest()
    .key(d => d.alliance)
    .sortKeys(d3.ascending)
    .entries(parties)
    .map(g => ({
      id: g.key,
      seats: g.values
    }));
  
  $g.datum(nest)
    .call(parliament);

  $g_annotation
    .append('line')
    .attr('class', 'line majority')
    .style('stroke', 'black')
    .attr('x1', width/2)
    .attr('x2', width/2)
    .attr('y1', margin.top)
    .attr('y2', (width/2) - (width/2 * 0.4) + margin.top);

  $g_annotation
    .append('path')
    .attr('d', symbol.type(d3.symbolTriangle))
    .attr('transform', `translate(${width/2}, ${margin.top-7}) rotate(-180)`)

  $g_annotation
    .append('text')
    .attr('x', width/2)
    .attr('y', margin.top)
    .attr('dy', -20)
    .attr('text-anchor', 'middle')
    .text('272 majority')

  parliament.on('click', d => {
    console.log(d.data.constituency)
  })
}

function init() {
  d3.csv('india-election-2019-results.csv').then(setupChart);
	}

init();

</script>
</body>