let census;
let db;

let f = 0;
let industries;

function countField(db, field) {
	let dictionary = [];
	let c = 0;

	for (var i = 0; i < db.length; i++) {
		industries = db[i][field];
		categories = industries.split("|");
		for (var j = 0; j < categories.length; j++) {
			if (!(categories[j] in dictionary) ) {
				dictionary[categories[j]] = 0;
				c++;
			} else {
				dictionary[categories[j]] += 1;
			}
		}
	}
	dictionary.length = c;
	return dictionary;

}

let s;

function salaryToNumber(str) {

	let final = 0;
	str = str.replaceAll(",", "");
	s = str;
	if (str.indexOf(" to ") != -1) {
		intervals = str.split(" to ");
		intervals[0] = parseInt(intervals[0].substr(1, intervals[0].length));
		intervals[1] = parseInt(intervals[1].substr(1, intervals[1].length));

		final = (intervals[0] + intervals[1]) /2;

	} else if (str.substr(str.length-1, str.length) == "+") {
		final = 200000;
	} else if (str.substr(0, 4) == "Less") {
		final = 25000;
	}

	return final;
}

let dictionary = [];
	let count_salary = [];
	let count;
let avg;

function averageSalary(db) {
	dictionary = [];
	count_salary = [];
	let c = 0;

	for (var i = 0; i < db.length; i++) {
		hours = db[i]["work_hours"];
		if (!(hours in dictionary) ) {
			dictionary[hours] = 0;
			count_salary[hours] = 0;
			c++;
		} else {
			dictionary[hours] += salaryToNumber(db[i]["salary"]);
			count_salary[hours] += 1;
		}
		
	}
	dictionary.length = c;


	console.log(dictionary);

	for (var i = 0; i < dictionary.length; i++) {
		console.log(dictionary[Object.keys(dictionary)[i]]);
		dictionary[Object.keys(dictionary)[i]] = dictionary[Object.keys(dictionary)[i]] / count_salary[Object.keys(dictionary)[i]];
	}

	console.log(dictionary);

	return dictionary;

}



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

	db = data;
	console.log(db);

	count = countField(db, "industries");
	console.log(count);

	byHours = d3.group(db, d => d.work_hours);
	salaryAvgByHour = [];
	avg = averageSalary(db);


	for (var i = db.length - 1; i >= 0; i--) {
		db[i]
	}

	canvas1 = d3.select("#canvas1").append("svg")
	.attr("class", "graph")
	.attr("id", "industries");

	industries = canvas1.append("g");

	industries.selectAll("text")
	.data(count)
	.enter()
	.append("text")
	.attr("x", function() {
		return 200+Math.random()*900;
	})
	.attr("y", function(d, i) {
		return 100+Math.random()*400;
	})
	.style("font-size", function(d, i) {
		return count[Object.keys(count)[i]] / 60;
	})
	.text(function (d, i) {
		if (Object.keys(count)[i] == "Digital products + services (web design, app design, software design)") {
			return "Digital products + services"
		} else {
			return Object.keys(count)[i];
		}
	});

	canvas2 = d3.select("#canvas2").append("svg")
	.attr("class", "graph")
	.attr("id", "salary");

	salary = canvas2.append("g");
	salary.selectAll("rect")
	.data(avg)
	.enter()
	.append("text")
	.text(function(d, i) {
		console.log(i);
		return avg[Object.keys(avg)[i]];
	});



})