angular.module('app').controller('ChartjsCtrl', function ($scope, $rootScope, $timeout, UniqueIdGenerator) {
    console.log("chartjs controller initialized");

    var loaded = false;

    $scope.chartId = UniqueIdGenerator.generateId();
    var ctx;
    var chart;
    var chartnameOld = null;

    function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]}

    $scope.instance.getAsImage = function () {
        var c = document.getElementById($scope.chartId);
        return c.toDataURL("image/png");
    }

    $scope.instance.print = function (config, chartname) {
        if (!loaded) {
            return;
        }

        if (chart && chartnameOld && chartname && chartnameOld == chartname) {
            chart.data.datasets.length = 0;

            for (var i = 0; i < config.data.datasets.length; i++) {
                var dataset = config.data.datasets[i];

                chart.data.datasets.push(dataset);
            }

            if (config.data.labels) {
                loadToArray(chart.data.labels, config.data.labels)
            }

            //$timeout(function () {
            chart.update();
            //});
        } else {
            if (chart) { //destroy old chart
                chart.destroy();

                chart = null;
            }


            //$timeout(function () {
            var canvas = document.getElementById($scope.chartId);
            ctx = canvas.getContext('2d');

            if (config) {
                if (config.options.xAxisTicksDurationInMS) {
                    config.options.tooltips = false;
                    config.options.scales = {
                        xAxes: [{
                            ticks: {
                                callback: function (value, index, values) {
                                    return $rootScope.formatDateTime(value);
                                }
                            }
                        }]
                    }
                }

                if (config.options.yAxisTicksMemory) {
                    config.options.scales = angular.merge(config.options.scales, {
                        yAxes: [{
                            ticks: {
                                callback: function (value, index, values) {
                                    if(value<0) return "";
                                    return formatBytes(value*1024*1024, 1);
                                }
                            }
                        }]
                    });
                }

                Chart.defaults.global.defaultFontColor = "#808080";

                chart = new Chart(ctx, config);

                /*
                                    var dpr = window.devicePixelRatio || 1;
                                    var bsr = ctx.webkitBackingStorePixelRatio ||
                                        ctx.mozBackingStorePixelRatio ||
                                        ctx.msBackingStorePixelRatio ||
                                        ctx.oBackingStorePixelRatio ||
                                        ctx.backingStorePixelRatio || 1;

                                    var ratio = dpr / bsr;

                                   
                                    //ctx.scale(ratio, ratio);
                                    canvas.width = $scope.width * ratio;
                                    canvas.height = $scope.height * ratio;
                                    canvas.style.width = $scope.width + "px";
                                    canvas.style.height = $scope.height + "px";

                                    chart.resize(canvas.width* ratio, canvas.height* ratio);
                                    */
            } else {
                ctx = document.getElementById($scope.chartId).getContext('2d');
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText("N/A", ctx.canvas.clientWidth / 2, ctx.canvas.clientHeight / 2);
                ctx.restore();
            }
            //});
        }

        chartnameOld = chartname;
    }

    $timeout(function () {
        if ($scope.afterInit) {
            $scope.afterInit();
        }

        loaded = true;
    });

    $scope.$on("$destroy", function () {
        UniqueIdGenerator.removeId($scope.chartId);
    });
});