

// Settings for the curration itself
// Independant of the data that was gathered
var currationSettings = {
	url : '<a href="https://soundcloud.com/aethernote">Andrew’s Favorites</a>',
	totalLikes : 0,
	showAmount : 50,
	tagAmount : 0
};

/* Define variables */
var trackTiles = document.getElementsByClassName("track-tiles");
var data;

/* Get our JSON */
function loadJSON(path, success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

loadJSON('data.json',
     function(jsonData) {
     	dataReadyForApp(jsonData);
     },
     function(xhr) { 
     	console.error(xhr); 
     }
);

function setStatistics(jsonData) {
	currationSettings.tagAmount = jsonData.genreTag.length;

	// Define DOM
	var statTrackAmount = document.getElementsByClassName("stat-track-amount")[0];
	var statTagAmount = document.getElementsByClassName("stat-tag-amount")[0];
	var statUser = document.getElementsByClassName("stat-user")[0];

	var statMostCommonTag = document.getElementsByClassName("stat-most-common-tag")[0];
	var statMostCommonTagAmount = document.getElementsByClassName("stat-most-common-tag-amount")[0];
	var chartGenres = document.getElementsByClassName("chart-genres")[0];
	var tagGenres = document.getElementsByClassName("tag-genres")[0];

	var condensedTags = uniq(jsonData.genreTag);

	var mostCommonTag = mode(jsonData.genreTag)[0];
	var mostCommonTagAmount = mode(jsonData.genreTag)[1];
	var tagMap = mode(jsonData.genreTag)[2];

	// Get all the unique values from the array
	// with no duplicates
	function mode(array) {
	    if(array.length == 0)
	        return null;
	    var modeMap = {};
	    var maxEl = array[0], maxCount = 1;
	    var uniques = [];

	    for(var i = 0; i < array.length; i++)
	    {
	        var el = array[i];
	        if(modeMap[el] == null) {
	            modeMap[el] = 1;
	        }
	        else {
	            modeMap[el]++;  
	        }
	        if(modeMap[el] > maxCount)
	        {
	            maxEl = el;
	            maxCount = modeMap[el];
	        }
	    }

	    return [maxEl, maxCount, modeMap];
	}

	// Returns sorted array from object
	function sortTagMap (tagMap) {
		var sortable = [];

		for (var vehicle in tagMap) {
		    sortable.push([vehicle, tagMap[vehicle]])
		}
		sortable.sort(function(a, b) {
		    return a[1] - b[1]
		})

		return sortable;
	}

	tickUp(statTrackAmount, jsonData.artists.length);
	tickUp(statTagAmount, getPercentage(jsonData.artists.length, condensedTags.length));
	
	statUser.innerHTML = currationSettings.url;		
	// statMostCommonTag.innerHTML = mostCommonTag;

	// Store the Chart Markup
	var sortedTagsAscending = sortTagMap(tagMap).reverse();
	var sortedTagsDescending = sortTagMap(tagMap);

	// console.log(sortedTagsAscending);

	var chartMarkupTopTags = "";
	var highestVal = sortedTagsAscending[0][1];

	for (var i = 0; i < 5; i++) {
		chartMarkupTopTags += (
		'<div class="chart-item">' +
			'<a href="https://soundcloud.com/tags/' + sortedTagsAscending[i][0] + '" target="0" class="chart-internal">' +
			'<div class="chart-item-name">#' + sortedTagsAscending[i][0] +
				'</div>' +
				'<div class="chart-item-tag">' + sortedTagsAscending[i][1] + 
			'</div>' +
			'</a>' +
			'<div class="chart-bar" style="' + 'max-width:' + getPercentage(highestVal, sortedTagsAscending[i][1]) + '%;">' + '</div>' +
		'</div>');
	}
	chartGenres.innerHTML = chartMarkupTopTags;

	var chartMarkupBottomTags = "";
	var tagsOnlyAppearingOnce = []; 

	// Generate an array of the files
	for (var i = 0; i < sortedTagsDescending.length; i++) {

		if (sortedTagsDescending[i][1] <= 3) {
			tagsOnlyAppearingOnce.push(sortedTagsDescending[i][0]);
		}
	}

	// Add 10 random items
	for (var i = 0; i < 10; i++) {

		var randomIndex = Math.floor(Math.random() * tagsOnlyAppearingOnce.length);

		chartMarkupBottomTags += (
		'<a href="https://soundcloud.com/tags/' + tagsOnlyAppearingOnce[randomIndex] + '" class="tag-item">#' +
			tagsOnlyAppearingOnce[randomIndex] +
		'</a>');
	}

	tagGenres.innerHTML = chartMarkupBottomTags;
}

/* Utility Functions */
function getPercentage(numTotal, numPart) {
	return ((numPart / numTotal) * 100).toFixed(0);
}

function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}

function tickUp (element, endValue) {
	var maxVal = endValue;
	var counter = 0;
	var start = null;
	
	function step(timestamp) {
	
	if (!start) start = timestamp;
		var progress = timestamp - start;

		if ((progress < 10000)) {
			if (counter < maxVal) {
				counter++;
				element.innerHTML = counter;
				window.requestAnimationFrame(step);
			}
		}
	}
	window.requestAnimationFrame(step);
}

function dataReadyForApp (jsonData) {
	setStatistics(jsonData);
}


function setHTML (jsonData) {
	
	var artists = jsonData.artists;
	var trackTitles = jsonData.trackTitles;
	var trackArt = jsonData.trackArt;
	var likes = jsonData.likes;
	var reposts = jsonData.reposts;
	var url = jsonData.url;
	var genreTag = jsonData.genreTag;

	var templateString = ``;

	var svgIconLikes = `<svg width="11px" viewBox="0 0 21 19" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
    <!-- Generator: Sketch 3.4.2 (15855) - http://www.bohemiancoding.com/sketch -->
    <title>Fill 1</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
        <path d="M10.8391442,18.3740185 C10.7376271,18.4501563 10.6379228,18.4991021 10.5110264,18.4991021 C10.3859429,18.4991021 10.2608593,18.4501563 10.1847215,18.3740185 L2.65795352,10.6315267 C-0.94227796,7.03129525 -0.405687568,3.36580277 1.44881233,1.51130287 C3.74019833,-0.778270324 7.16458769,-0.334133006 9.45416089,1.95725299 C9.88198296,2.38326226 10.2137263,3.45463024 10.4910856,3.95859013 C10.7684448,3.45463024 11.1418827,2.38326226 11.567892,1.95725299 C13.859278,-0.359512281 17.3162978,-0.771019102 19.6312503,1.54393337 C21.3497898,3.26247287 21.9643308,7.03129525 18.3659121,10.6315267 L10.8391442,18.3740185 Z" id="Fill-1" fill="#FEFEFE" sketch:type="MSShapeGroup"></path>
    </g>
	</svg>`;

	var svgIconResposts = `<svg width="12px" viewBox="0 0 24 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
    <!-- Generator: Sketch 3.4.2 (15855) - http://www.bohemiancoding.com/sketch -->
    <title>Fill 1 + Fill 3</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
        <g id="Fill-1-+-Fill-3" sketch:type="MSLayerGroup" fill="#FEFEFE">
            <path d="M21.8418462,10 L19.2,10.5074286 C18.8935385,10.5074286 18.6461538,10.7371429 18.6461538,11.02 L18.6461538,13.3771429 L18.7661538,13.9651429 L18.1864615,13.8537143 L5.61046154,13.8537143 L4.87384615,14.1382857 L4.97169231,13.3411429 L4.97169231,11.9577143 C4.97169231,11.7485714 4.83692308,11.5617143 4.63015385,11.4811429 C4.42338462,11.4022857 4.18523077,11.4451429 4.02646154,11.5942857 L0.160615385,15.1857143 C-0.0535384615,15.388 -0.0535384615,15.712 0.160615385,15.9125714 L4.02646154,19.504 C4.13169231,19.6034286 4.27384615,19.6548571 4.41784615,19.6548571 C4.48984615,19.6548571 4.56184615,19.6428571 4.63015385,19.6171429 C4.83692308,19.5365714 4.97169231,19.3497143 4.97169231,19.1422857 L4.97169231,17.6628571 L4.86830769,16.8965714 L5.57169231,17.2445714 L21.8418462,17.2445714 C22.1483077,17.2445714 22.3956923,16.9908571 22.3956923,16.708 L22.3956923,10.5142857 C22.3956923,10.2297143 22.1483077,10 21.8418462,10" id="Fill-1" sketch:type="MSShapeGroup"></path>
            <path d="M1.55384615,9.65485714 L4.19569231,9.14742857 C4.50215385,9.14742857 4.74953846,8.91771429 4.74953846,8.63485714 L4.74953846,6.27771429 L4.62953846,5.68971429 L5.20923077,5.80114286 L17.7852308,5.80114286 L18.5218462,5.51657143 L18.424,6.31371429 L18.424,7.69714286 C18.424,7.90628571 18.5587692,8.09314286 18.7655385,8.17371429 C18.9723077,8.25257143 19.2104615,8.20971429 19.3692308,8.06057143 L23.2350769,4.46914286 C23.4492308,4.26685714 23.4492308,3.94285714 23.2350769,3.74228571 L19.3692308,0.150857143 C19.264,0.0514285714 19.1218462,0 18.9778462,0 C18.9058462,0 18.8338462,0.012 18.7655385,0.0377142857 C18.5587692,0.118285714 18.424,0.305142857 18.424,0.512571429 L18.424,1.992 L18.5273846,2.75828571 L17.824,2.41028571 L1.55384615,2.41028571 C1.24738462,2.41028571 1,2.664 1,2.94685714 L1,9.14057143 C1,9.42514286 1.24738462,9.65485714 1.55384615,9.65485714" id="Fill-3" sketch:type="MSShapeGroup"></path>
        </g>
    </g>
	</svg>`;

	var htmlToAdd = "";

	// Add HTML for each item
	// This is kind of expensive
	for(var i = 0; i < artists.length; i++) {
	    var tile = "<a href='" + url[i] + "' target='0' class='tile'><div class='tile-internal'>" + '<div class="art" style="background-image: url(../images/trackArt' + [i + 1] + '.jpg");></div><div class="info">' +
	    "<div class='track-info'>" + artists[i] + " – " + trackTitles[i] + "</div>" +
	    "<div class='track-metadata'>" + svgIconLikes + likes[i] + "</div>" +
	    "</div></div></a>";

	    htmlToAdd += tile;
	}

	// Add them all to the HTML.
	trackTiles[0].innerHTML = htmlToAdd;
}