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

    var loaded = false;
    var chart = null;

    $scope.chartId = UniqueIdGenerator.generateId();

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

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

        if(chart) {
            chart.updateOptions(angular.copy(config));
            
        } else {
            chart = new ApexCharts(document.querySelector("#"+$scope.chartId), angular.copy(config));

            chart.render();
        }

        window.dispatchEvent(new Event('resize'));
    }

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

        loaded = true;
    });

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