/**
 * Tag_valController
 *
 * @description :: Server-side logic for managing tag_vals
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var mysqlDate = function(d){
	var year = d.substring(0,4);
	var month = d.substring(4,6);
	var day = d.substring(6,8);
	var hour = d.substring(9,11);
	var min = d.substring(11,13);
	var sec = d.substring(13,15);
	return "".concat(year, "-", month, "-", day, " ", hour, ":", min, ":", sec);
};

var createCSVrow = function(header, dataRow){
    var i = header.indexOf(dataRow.tagID);
	// for (var x = 0; x < header.length; x++){
	// 	console.log(dataRow.id, header[x], parseInt(dataRow.tagID) == parseInt(header[x]));
	// }
    var csvRow = dataRow.id.toString() + ',' + dataRow.createdAt + ',';
    if(i >= 0){
        var j = 2;
        while (j < header.length){
            if (j == i){
                csvRow = csvRow + dataRow.val.toString() + ',';
            } else {
                csvRow = csvRow + ',';
			}
            j++;
		}
        csvRow = csvRow.slice(0, -1) + '\u000d';
        return csvRow;
	}
};

module.exports = {
	latest: function(req, res){
		var query = "SELECT v1.id as id, v1.createdAt as dtime, t.id as t_id, t.name as name, t.tag as tag, v1.val as val, t.units as units, t.description as description, t.minExpected as minExpected, t.maxExpected as maxExpected FROM tag_vals v1 INNER JOIN tags t ON t.id = v1.tagID WHERE v1.id = (SELECT v2.id FROM tag_vals v2 WHERE v2.tagID = v1.tagID ORDER BY v2.id DESC LIMIT 1) ORDER BY t.id";
		Tag_val.query(query, function(err, results){
			if (err) return res.serverError(err);
			return res.ok(results);
		});
	},

	clearSingleTagData: function(req, res){
		var where = {'where':{'tagID': req.params.id}};
		Tag_val.destroy(where).exec(function(err){
			if (err) return res.serverError(err);
			return res.ok();
		});
	},

	clearAllTagData: function(req,res){
		var where = {'where':{'id': {">": 0}}};
		Tag_val.destroy(where).exec(function(err){
			if (err) return res.serverError(err);
			return res.ok();
		});
	},

	csvSingle: function(req, res){
		var w = {'where':{'tagID': req.params.id, 'createdAt': {">":mysqlDate(req.params.start), "<": mysqlDate(req.params.end)}}};
		Tag_val.find(w).exec(function(err, rows){
			if (err) return res.serverError(err);
			Tag.find({'where':{'id': req.params.id}}).exec(function(tag_err, tag_names){
				if (tag_err) return res.serverError(tag_err);
				var h = ['id', 'DateAdded'];
				var hid = ['id', 'DateAdded'];
				for (var j = 0; j < tag_names.length; j++){
					h.push(tag_names[j].name);
					hid.push(tag_names[j].id);
				}
				var csvString = "";
				csvString = csvString + h.join(',') + '\u000d';

				var i = 0;
				while (i < rows.length){
					csvString = csvString + createCSVrow(hid, rows[i]);
					i++;
				}
				res.set('Content-Type', 'text/csv');
				res.set('Content-Disposition', 'attachment;filename=tagdata.csv');
				res.send(csvString);
			});
		});
	},

	csvAll: function(req, res){
		Tag_val.find().exec(function(err, rows){
			if (err) return res.serverError(err);
			Tag.find().exec(function(tag_err, tag_names){
				if (tag_err) return res.serverError(tag_err);
				var h = ['id', 'DateAdded'];
				var hid = ['id', 'DateAdded'];
				for (var j = 0; j < tag_names.length; j++){
					h.push(tag_names[j].name);
					hid.push(tag_names[j].id);
				}
				var csvString = "";
				csvString = csvString + h.join(',') + '\u000d';

				var i = 0;
				while (i < rows.length){
					csvString = csvString + createCSVrow(hid, rows[i]);
					i++;
				}
				res.set('Content-Type', 'text/csv');
				res.set('Content-Disposition', 'attachment;filename=tagdata.csv');
				res.send(csvString);
			});
		});
	}
};
