window.onload = function () {
    var app = new Vue({
        el: '#app',
        data: {
        }
    });
};

Vue.component('disk_space', {
    data: function () {
        return {
            items: [],
            lastPercentage: 0.0
        }
    },
    props: [],

    template: '<div id="availableStorage" >\
                    <div class="row">\
                        <div v-for="(item, index) in items" class="col-lg-2 col-sm-3 col-xs-6 col-4">\
                            <div class="cover thumbnail">\
                                <canvas v-bind:id="item.ID"></canvas>\
                                <div class="caption-btm text-center"><p>{{ item.summary }}</p></div>\
                            </div>\
                        </div>\
                    </div>\
                </div>',
    mounted: function () {
        var self = this;
        self.reload();
    },    
    updated: function () {
        var self = this;        
        self.items.forEach(function (item) {
            // draw chart
            var percentFree = ((100.0 / item.total) * item.free).toFixed(0);
            var gbFree = (item.free / 1000000000).toFixed(2);
            var ctx = document.getElementById(item.ID).getContext('2d');
            var chart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ["", ""],
                    datasets: [{
                        backgroundColor: [
                            "#2db7fc",
                            "#d1d3d2",
                        ],
                        data: [100 - percentFree, percentFree]
                    }]
                }
            });
        });
    },
    methods: {
        reload() {
            var self = this;
            Chart.defaults.global.legend.display = false;
            var url = 'services/service?method=system.space&format=json&random=' + Math.random();
            $.getJSON(url, function (data) {
                var update = true;       
                var percentage = 0.0;
                data.forEach(function (spaceData) {
                    spaceData.ID = "availableSpaceChart-" + spaceData.name;
                    var percentFree = ((100.0 / spaceData.total) * spaceData.free).toFixed(0);
                    var gbFree = (spaceData.free / 1000000000).toFixed(2);
                    spaceData.summary = spaceData.name + ' (' + percentFree + '% free - ' + gbFree + 'GB)';                    
                    percentage = percentFree;
                    if (self.lastPercentage === percentage) {
                        update = false;
                    }
                });
                if (update) {
                    self.items = data;
                }
                self.lastPercentage = percentage;
            });
        }
    }
});
