poconsole.controller('tagValsCtrl', function($scope, $route, $http, $routeParams, Page, $log, Tag, dateConversion) {
	Page.setTitle('Tag Series');
    Page.setPage('tags');
    var colors = ['#d7191c','#fdae61','#abdda4','#2b83ba'];

    if (!$routeParams.endDatetime){
        $scope.endDatetime = new Date();
    } else {
		$scope.endDatetime = Date.parse(dateConversion.sqliteDate($routeParams.endDatetime));
    }

    if (!$routeParams.startDatetime){
        $scope.startDatetime = new Date();
        $scope.startDatetime.setHours($scope.endDatetime.getHours() - 2);
    } else {
		$scope.startDatetime = Date.parse(dateConversion.sqliteDate($routeParams.startDatetime));
    }
    $log.info({start: $scope.startDatetime, end:$scope.endDatetime});

    $scope.loadTagVals = function(sDTime, eDTime){
        // loads the tag values into a format usable by the chart object
		$scope.startDatetime = sDTime;
		$scope.endDatetime = eDTime;
        console.log({s: sDTime, e: eDTime});

		// $log.info({start: sDTime, end:eDTime});
        $scope.loading = true; // Show the loading div while getting the values

        var tags_to_get = $routeParams.tagID.split(",").toString(); // the tagID parameter could be a single tag or a list of tags.
        $scope.tags_to_get = tags_to_get;

        // the get multiple tags will return the db entry for all tags in the list
    	var getMultipleTags = Tag.getMultipleTags(tags_to_get);
    	getMultipleTags.then(function(tagData){
			var tagDefData = tagData.tag; // assigns the tag definition data to tagDefData

            //get the tag history between the two datetimes for the specified tags
		    var getTagHistoryBetween = Tag.getTagHistoryBetween(tags_to_get, dateConversion.pythonDate(sDTime), dateConversion.pythonDate(eDTime));
		    getTagHistoryBetween.then(function(data) {
                // this map takes all values that were returned from getTagHistoryBetween and creates an object with all possible tags
                // for all tags other than the one measured, the value is null
				$scope.table_vals = data.vals.map(function(x){
					var ob =  {id: x._id, tag: x.tag, dtime: new Date(x.created_on)};
                    for(var t = 0; t< tagDefData.length; t++){
                        if (tagDefData[t].name === x.tag.name){
                            ob[tagDefData[t].name] = x.value;
                        } else {
                            ob[tagDefData[t].name] = null;
                        }
                    }
                    return ob;
				});

                // we need to create an object that will hold "joined" data from each tag.
                // the chart object needs data to have all parameters {x:$$$, y1:^^^, y2:###, ...}

                // create an empty object for each tag by name
                // tagName : {dtimes:[], vals:[], ob:{}}
                // dtimes: all datetimes with values for the tag
                // vals: all values for the tag
                // ob:
                var split_vals = {};
                var all_datetimes = [];
                for(var t=0; t< tagDefData.length; t++){
                    split_vals[tagDefData[t].name] = {};
                    split_vals[tagDefData[t].name].dtimes = [];
                    split_vals[tagDefData[t].name].vals = [];
                    split_vals[tagDefData[t].name].lookup = {};
                }

                // take each value returned from getTagHistoryBetween and sort it into an object inside split_vals
                for (var i = 0; i< data.vals.length; i++){
                    split_vals[data.vals[i].tag.name].lookup[data.vals[i].created_on]= data.vals[i].value; // a lookup table for values by datetime
                    split_vals[data.vals[i].tag.name].dtimes.push(data.vals[i].created_on);
                    split_vals[data.vals[i].tag.name].vals.push(data.vals[i].value);
                    // use all_datetimes to track a list of every datetime with a stored value
                    if (all_datetimes.indexOf(data.vals[i].created_on) == -1){
                        all_datetimes.push(data.vals[i].created_on);
                    }
                }

                $scope.data = {};
                // for data uniformity, set the first data point in $scope.data.vals to the
                // first data point stored for each tag at the earliest time for all tags
                $scope.data.vals = [{dtime:new Date(all_datetimes[0])}];
                for (var ta in split_vals) {
                    $scope.data.vals[0][ta] = split_vals[ta].vals[0];
                }

                // loop through all datetimes to create objects
                for (var j = 0; j < all_datetimes.length; j++){
                    var valsAtTime = {dtime: new Date(all_datetimes[j])};
                    for(var tag in split_vals){
                        if(split_vals[tag].lookup[all_datetimes[j]] === undefined){
                            // if no value for the datetime is found in the lookup object, set the value for the tag equal to the last value stored
                            valsAtTime[tag] = $scope.data.vals[j][tag];
                        } else {
                            // if there is a value for the datetime in the lookup object, use it for the tag value
                            valsAtTime[tag] = split_vals[tag].lookup[all_datetimes[j]];
                        }
                    }
                    $scope.data.vals.push(valsAtTime);
                }
	    		$scope.error = false;
		    	$scope.loading = false;
	    		$scope.options = {
					series: [

					],
					axes: {
						x: {
							key: "dtime",
							type: "date"
						}
					}
				};
                for(var i2 = 0; i2< tagDefData.length; i2++){
                    $scope.options.series.push({
                        axis: "y",
                        dataset: "vals",
                        key: tagDefData[i2].name,
						id: i2.toString(),
                        label: tagDefData[i2].name,
                        // color: "#1f77b4",
                        color: colors[i2 % colors.length],
                        type: ['line'],
                        drawDots:false
                    });
                }
				console.log($scope.options);
		    });
    	});
    };
    $scope.loadTagVals($scope.startDatetime, $scope.endDatetime);
});
