let spotify;

let WIDTH = window.innerWidth;
let HEIGHT = window.innerHeight * 1.2;

let minim = Math.min(WIDTH, HEIGHT);

let max_dur = 0;
let min_dur = 0;


let x = 0;
let ang = 0;

let more;


noise.seed(Math.random());


dist_normalize = d3.scaleLinear() 
.domain([0, minim/2.5])
.range([0, 1]);


vibration_scale = d3.scalePow()
.exponent(6)
.domain([0, 0.8, 1])
.range([0, 8, 20]);

size_scale = d3.scaleLinear()
.domain([0, 1])
.range([2, 9]);

var color_gradient = d3.scaleLinear()
.domain([-20, -7, -2])
.range(['darkred', 'orange', "white"]);









//Funções tiradas de forums (Stackoverflow)
function getPos(ele){
	var x=0;
	var y=0;
	while(true){
		x += ele.offsetLeft;
		y += ele.offsetTop;
		if(ele.offsetParent === null){
			break;
		}
		ele = ele.offsetParent;
	}
	return [x, y];
}

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
	var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

	return {
		x: centerX + (radius * Math.cos(angleInRadians)),
		y: centerY + (radius * Math.sin(angleInRadians))
	};
}

function describeArc(x, y, radius, startAngle, endAngle){

	var start = polarToCartesian(x, y, radius, endAngle);
	var end = polarToCartesian(x, y, radius, startAngle);

	var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

	var d = [
	"M", start.x, start.y, 
	"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
	].join(" ");

	return d;       
}


function dist(x1, y1, x2, y2) {
	var a = x1 - x2;
	var b = y1 - y2;

	var c = Math.sqrt( a*a + b*b );
	return c;
}


function millisToMinutesAndSeconds(millis) {
	var minutes = Math.floor(millis / 60000);
	var seconds = ((millis % 60000) / 1000).toFixed(0);
	return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}


//Fim de funções tiradas de forums


function parallax(id, div) {

	let pageScroll = window.pageYOffset + window.innerHeight;

	let point = window.pageYOffset + (window.innerHeight/2);

	let el_pos = getPos(document.getElementById(id))[1] + (document.getElementById(id).offsetHeight/2);

	let dif = el_pos - point;

	if (div < 0) {
		dif = -dif;
	}

	elemento = document.getElementById(id);
	elementsize = elemento.getBoundingClientRect().top;
	elemento.style.transform = "translateY( "+ dif / Math.abs(div) + "px)";
}

function clear(svg) {
	svg.select(".ring")
	.style("opacity", 0);

	svg.select(".line")
	.style("opacity", 0);

	svg.selectAll("line")
	.style("opacity", 0);

	svg.selectAll("g")
	.style("opacity", 1);

	svg.selectAll("text")
	.style("opacity", 0);

	svg.select(".e")
	.style("opacity", 0);

	svg.select(".bpm_ico")
	.style("opacity", 0);
}


function coords(svg, ev) {

	let mouseX = ev.clientX;
	let mouseY = ev.clientY - document.getElementById("main").getBoundingClientRect().y;

	ang = (Math.atan2((WIDTH/2)-mouseX, (HEIGHT/2)-mouseY));

	let dista = dist(WIDTH/2, HEIGHT/2, mouseX, mouseY);

	if (dista <= minim/2) {

		if (dista >= minim/2.5) {
			dista = minim/2.5;
		}

		svg.select(".ring")
		.attr("stroke", "white")
		.style("opacity", 1)
		.attr("d", describeArc(WIDTH/2, HEIGHT/2, minim/2.5, 180-(ang*(180/Math.PI))+180, 360+180));

		svg.select(".line")
		.attr("stroke", "white")
		.attr("x1", WIDTH/2)
		.attr("y1", HEIGHT/2)
		.style("opacity", 1)
		.attr("x2", (WIDTH/2)  + Math.sin((ang + Math.PI)) * ((dist_normalize(dista).toString().substr(0, 4)*minim/2.5)))
		.attr("y2", (HEIGHT/2) + Math.cos((ang + Math.PI)) * ((dist_normalize(dista).toString().substr(0, 4)*minim/2.5)));

		svg.selectAll("g")
		.style("opacity", 0.5);

		let trX = (WIDTH/2)  + Math.sin((ang + Math.PI) + 0.3) * ((dist_normalize(dista).toString().substr(0, 4)*minim/2.5)/2);
		let trY = (HEIGHT/2) + Math.cos((ang + Math.PI) + 0.3) * ((dist_normalize(dista).toString().substr(0, 4)*minim/2.5)/2);

		let rot_ang = ((ang*(180/Math.PI))+90);

		if (rot_ang > 90) {
			rot_ang += 180;
		}

		let e = svg.select(".e");

		e.attr("transform", "translate("+trX+", "+trY+") rotate("+ -(rot_ang)+" 0, 0)")
		.style("opacity", 1);

		e.select(".radius")
		.style("opacity", 1)
		.text((dist_normalize(dista).toString().substr(0, 4)));


		svg.select(".angle")
		.text( Math.floor(parseFloat(ang_to_duration((ang + Math.PI))) ))
		.attr("x", (WIDTH/2) + -20 + Math.sin(ang + Math.PI) * minim/2.1)
		.attr("y", (HEIGHT/2) + Math.cos(ang + Math.PI) * minim/2.1)
		.style("opacity", 1);

		svg.select(".guide_1")
		.attr("x1", WIDTH/2)
		.attr("y1", HEIGHT/2)
		.attr("x2", (WIDTH/2))
		.attr("y2", (HEIGHT/2) + minim/2.5)
		.style("opacity", 0.5);

		svg.select(".guide_2")
		.attr("x1", WIDTH/2)
		.attr("y1", HEIGHT/2)
		.attr("x2", (WIDTH/2)  + Math.sin(ang + Math.PI) * minim/2.5)
		.attr("y2", (HEIGHT/2) + Math.cos(ang + Math.PI) * minim/2.5)
		.style("opacity", 0.5);

		svg.select(".bpm_ico")
		.style("opacity", 1)
		.attr("x", (WIDTH/2) + -20 + Math.sin(ang + Math.PI) * minim/2.1)
		.attr("y", (HEIGHT/2) + Math.cos(ang + Math.PI) * minim/2.1);

	} else {
		clear(svg);
	}

			
}


function draw() {

	spotify = spotify.sort(function(a, b) {
		return d3.ascending(a.tempo, b.tempo);
	})

	min_bpm = d3.min(spotify, function (d) {
		return +d.tempo;
	});

	max_bpm = d3.max(spotify, function (d) {
		return +d.tempo;
	});


	let bpm_range = [min_bpm, max_bpm];
	let ang_range = [0, (Math.PI*2)];

	duration = d3.scaleLinear()
	.domain(bpm_range)
	.range(ang_range);

	ang_to_duration = d3.scaleLinear()
	.domain(ang_range)
	.range(bpm_range);



	let svg = d3.select("body").select("#main").append("svg")
	.attr("width", WIDTH)
	.attr("height", HEIGHT)
	.attr("class", "graph");

	let g = svg.append("g");

	let step = (Math.PI*2) / spotify.length;

	let e_label = svg.append("g");

	e_label.attr("class", "e");

	e_label.append("text")
	.text(ang)
	.attr("text-anchor", "middle")
	.attr("fill", "white")
	.attr("class", "radius")
	.attr("x", 0)
	.attr("y", 0);

	e_label.append("image")
	.attr("class", "energy_ico")
	.attr("href", "energy.svg")
	.attr("transform", "translate(-43, -18)")
	.attr("width", 30)
	.attr("height", 30);

	svg.append("text")
	.text(ang)
	.attr("fill", "white")
	.attr("class", "angle")
	.attr("x", 0)
	.attr("y", 0);


	document.getElementById("main").children[0].onmousemove = function(ev) {
		coords(svg, ev);
	};
	document.getElementById("main").children[0].onmouseleave = function () {
		clear(svg);
	};


	svg.append("path")
	.attr("d", describeArc(WIDTH/2, HEIGHT/2, minim/2.4, ang, ang+100))
	.attr("class", "ring")
	.attr("fill", "transparent")
	.attr("stroke", "transparent")
	.attr("stroke-width", 5);

	svg.append("line")
	.attr("class", "line")
	.attr("fill", "transparent")
	.attr("stroke", "transparent")
	.attr("stroke-width", 5);

	svg.append("line")
	.attr("class", "guide_1")
	.attr("fill", "transparent")
	.attr("stroke", "white")
	.attr("stroke-width", 1);

	svg.append("line")
	.attr("class", "guide_2")
	.attr("fill", "transparent")
	.attr("stroke", "white")
	.attr("stroke-width", 1);

	svg.append("image")
	.attr("class", "bpm_ico")
	.attr("href", "bpm.png")
	.attr("transform", "translate(-33, -18)")
	.attr("width", 21)
	.attr("height", 21);

	g.selectAll("circle")
	.data(spotify)
	.enter()
	.append("circle")
	.attr("artist", function (d) {
		return d.artist;
	})
	.attr("dance", function(d) {
		return d["danceability"];
	})
	.attr("cx", function(d, i) {
		return (WIDTH/2) + Math.sin(duration(d.tempo))*((parseFloat(d["energy"])) * minim/2.5);
	})
	.attr("cy", function(d, i) {
		return (HEIGHT/2) + Math.cos(duration(d.tempo))*((parseFloat(d["energy"])) * minim/2.5);
	})
	.attr("r", function(d) {
		return size_scale(d.valence);
	})
	.attr("fill", function(d) {

		return color_gradient(d.loudness);
	})
	.attr("vibration", 0)
	.style("stroke-width", 2);


}

		d3.csv("spotify.csv").then(function(data) {

			spotify = data
			draw();

		})

		let main_graph;

//Animação das bolas
setTimeout(function() {
	main_graph = document.getElementById("main").children[0].children[0];

	setInterval(function() {

		more = parseFloat(window.getComputedStyle(document.getElementById("d_more")).opacity);
		x += 0.15*(more+0.1);
		document.getElementById("dance_lbl").style.transform = "translate("+ noise.simplex2(x, 2)*(more*10) +"px, "+(noise.simplex2(x, 555)*(more*10)) +"px) scale(0.3)";
		for (var i = main_graph.children.length - 1; i >= 0; i--) {
			dance = parseFloat(main_graph.children[i].getAttribute("dance"));
			vib = parseFloat(main_graph.children[i].getAttribute("vibration"));
			vib += dance/7;
			main_graph.children[i].setAttribute("vibration", vib);

			if (dance > 0.5) {
				v_scale = vibration_scale(dance);
				main_graph.children[i].style.transform = "translate("+ noise.simplex2(vib, dance*500)*v_scale +"px, "+ noise.simplex2(vib, dance*300)*v_scale +"px)";
			}
		}
	}, 30);

}, 1000); 




window.onscroll = function() {
	parallax("titulo", 2);
	parallax("desc", 4);
	parallax("legenda", 4);
}


