fs = require('fs');

var CSVStream=require('csv-streamer');


var parseNodes = function(data){
	var Nodes = [];
	
	data.toString().split('\n').forEach(function(d){
		Nodes.push('{ "name" : ' +d+'}');
	});

	return Nodes;
}

var parseLinks = function(data, nodesIndex){
	var Links= [];
	
	data.toString().split('\n').forEach(function(d){
		line = d.split('--');
		source = line[0].trim().replace(/\./g,"");
		//source = parseInt(source)-1;
		target = line[1].split('(')[0].trim().replace(/\./g,"");
		//target = parseInt(target)-1;
		weight = line[1].split(':')[1].split(')')[0].trim();
		Links.push('{ "source" : "' + String(source) + '" ,"target" : "' + String(target) + '", "value" : ' + weight + '}');
	});
	Links[Links.length-1] = Links[Links.length-1];
	//console.log(Links);

	return Links;
}

var createJSON = function(ToJSON, Metadata,SchemeGenes){
	var JsonString = '{ "metadata" : [' + Metadata.toString() + '],'+'\n"schemeGenes" : [' + SchemeGenes.toString() + '], \n"nodes" : ' + ToJSON[0] + ', \n"links" : [' + ToJSON[1] + ']}';
	JsonString = JsonString.replace(/\{"key"/g , '\n{"key"');
	JsonString = JsonString.replace(/\{ "source"/g , '\n{ "source"');
	//console.log(JsonString);
	return JsonString;
}


module.exports = function (nodes, links, metadata, key){
	var ToJSON = [];
	var csvNodes = new CSVStream({headers:true, delimiter:'\t'});
	var csvLinks = new CSVStream({headers:true, delimiter:'\t'});
	var csvMetadata = new CSVStream({headers:true, delimiter:'\t'});
	var Nodes = [];
	var Links = [];
	var ToWrite;
	var Metadata = [];
	var firstTime = true;
	var NodesIndex = {};
	var countIndex = 0;
	var found = false;
	var key = key;
	var SchemeGenes = [];
	var STlist = {};
	var STmetadata = {};


	csvMetadata.on('data',function(line){
		//line = JSON.stringify(line).replace(/\{/g , '\n{ "id":"' + idST + '",');
		var isolates = [];

		if(!found){
			for(var p in line){
				//console.log(key.toString().toLowerCase());
				//console.log(p.toString().toLowerCase());

				if (key.toString().toLowerCase() == p.toString().toLowerCase()){
					key = p;
					found =true;
					break
				}
			}
		}

		//console.log(String(String(line.file).toLowerCase()));

		if (STmetadata[String(line[key])] == null) STmetadata[String(line[key]).replace(/\./g,"")] = [];

		for (var params in line){
			if (firstTime) Metadata.push('"' + params + '"');

			isolates.push(line[params].replace(/\./g,""));
		}
		
		STmetadata[String(line[key]).replace(/\./g,"")].push(isolates);
		firstTime = false;


    	//Metadata.push(line);
	});

	// csvLinks.on('data',function(line){
 //    	Links.push(line);
	// });

	csvMetadata.on('end',function(){
		//var Nodes  = [];
		var found = false;
		var NodeKey;
		var firstTimeNodes = true;
		fs.createReadStream(nodes).pipe(csvNodes);

		csvNodes.on('data',function(line){

			if(!found){
			for(var p in line){
				//if (firstTimeNodes) SchemeGenes.push('"' + p + '"');
				//console.log(key.toString().toLowerCase());
				//console.log(p.toString().toLowerCase());

				if (key.toString().toLowerCase() == p.toString().toLowerCase()){
					NodeKey = p;
					found =true;
					break
				}
			}
		}

		if (firstTimeNodes){ 
			for(var p in line){
				//console.log(p);
				if (p != NodeKey) SchemeGenes.push('"' + p + '"');
				//console.log(key.toString().toLowerCase());
				//console.log(p.toString().toLowerCase());
			}
		}
		

			//idST += 1;
			//line = JSON.stringify(line).replace(/\{/g , '\n{ "id":"' + idST + '",');
			var newNode = { key : line[NodeKey].replace(/\./g,"") };

			NodesIndex[newNode['key']] = countIndex;


			var count = 0;
			for (var params in line){
				if (count != 0){
					if (newNode['profile'] == null) newNode['profile'] = [];
					newNode['profile'].push(line[params]);

				} 
				count +=1;
			}

			//console.log(STmetadata[String(newNode['key'])]);


			if (STmetadata[String(newNode['key'])] == null) newNode.isolates = [];
			else newNode.isolates = STmetadata[String(newNode['key'])];

			//console.log(newNode.isolates);

			//STlist[String(line.ST)].push(line);
			 

		   	Nodes.push(newNode);
		   	countIndex += 1;
		   	firstTimeNodes = false;
			});

		csvNodes.on('end',function(){
			//var Nodes  = [];
			// var Topass = ''
			// var count=0;
			// for (i in STlist){
			//   	Topass+= JSON.stringify(STlist[i]) + ','
			//   	count+=1;
			 	
			//   }
			//  Topass = Topass.substring(0, Topass.length - 1);
			//  Topass = Topass.replace(/\[\{/g , '\n[{')
			// // console.log(count);
			ToJSON.push(JSON.stringify(Nodes));

			fs.readFile(links, 'utf8', function(err, data){
		  		if (err) throw err;
		  		else Links = parseLinks(data, NodesIndex);
		  		ToJSON.push(Links);
		  		toWrite = createJSON(ToJSON, Metadata, SchemeGenes);

		  		fs.writeFile('./public/data/goeData.json', toWrite, function(err){
		  			if(err) {
		  		        return console.log(err);
		  		    }

		  		    console.log("The file was saved!");
		  		})
	 		});
			//ToJSON.push(JSON.stringify(STlist));
		})
		// var Topass = ''
		// var count=0;
		// for (i in STlist){
		//   	Topass+= '"' + i + '":' + JSON.stringify(STlist[i]) + ','
		//   	count+=1;
		 	
		//   }
		// Topass = Topass.substring(0, Topass.length - 1);
		// Topass = Topass.replace(/\[\{/g , '\n[{')
		// // console.log(count);
		// ToJSON.push(Topass);
		// //ToJSON.push(JSON.stringify(STlist));
		// toWrite = createJSON(ToJSON);
		// fs.writeFile('./public/data/goeData.json', toWrite, function(err){
 	// 		if(err) {
 	// 	        return console.log(err);
 	// 	    }

 	// 	    console.log("The file was saved!");
		// })
	})


	// csvLinks.on('end',function(){
	// 	ToJSON.push(JSON.stringify(Links));
	// 	toWrite = createJSON(ToJSON);
	// 	fs.writeFile('./public/data/goeData.json', toWrite, function(err){
 // 			if(err) {
 // 		        return console.log(err);
 // 		    }

 // 		    console.log("The file was saved!");
	// 	})
	// })

	fs.createReadStream(metadata).pipe(csvMetadata);
	//fs.createReadStream(links).pipe(csvLinks);

	// fs.readFile(nodes, 'utf8', function(err, data){
	// 	if (err) throw err;
	// 	else Nodes = parseNodes(data);
	// 	ToJSON.push(Nodes);


};