(function () {
    "use strict";

    angular.module('pos').factory('tools', factory);
    factory.$inject = [];

    function factory() {

        var _buildChart = function (elementId, yTitle, series, print) {
            ///elementId: id do elemento a ser populado
            ///yTitle: Título do eixo vertical
            ///series: Array de objetos com as configurações e dados da serie
            ///print: opcional - indica se é para impressão ou não

            ///return: bool retorna verdadeiro se as séries estiverem todas vazias.

            var datalabels = false;
            if (print)
                datalabels = true;

            var xDateType = false;
            var isEmpty = true;

            /*Por questão de compatibilidade e parsing do angularjs as datas devem ser enviadas via string no formato "Date.UTC(yyyy,MM,dd)".
            estas string serão convertidas em datas logo abaixo.*/
            for (var i = 0; i < series.length; i++) {
                if (series[i].data.length > 0) {
                    isEmpty = false;
                    if (series[i].data[0][0].toString().indexOf("Date.UTC") >= 0) {
                        xDateType = true;
                        for (var n = 0; n < series[i].data.length; n++)
                            series[i].data[n][0] = eval(series[i].data[n][0]);
                    }
                }
            }

            $(elementId).highcharts(
            {
                'chart': {
                    renderTo: elementId,
                    backgroundColor: 'transparent',
                    zoomType: 'x',
                },
                'credits': { enabled: false },
                'title': { text: '' },
                'subtitle': { text: '' },
                'exporting': { enabled: false },
                'plotOptions': {
                    area: { dataLabels: { enabled: datalabels } },
                    arearange: { dataLabels: { enabled: datalabels } },
                    areaspline: { dataLabels: { enabled: datalabels }, marker: { enabled: false } },
                    areasplinerange: { dataLabels: { enabled: datalabels } },
                    bar: { dataLabels: { enabled: datalabels } },
                    box: { dataLabels: { enabled: datalabels } },
                    bubble: { dataLabels: { enabled: datalabels } },
                    column: { dataLabels: { enabled: datalabels } },
                    columnrange: { dataLabels: { enabled: datalabels } },
                    errorbar: { dataLabels: { enabled: datalabels } },
                    funnel: { dataLabels: { enabled: datalabels } },
                    gauge: { dataLabels: { enabled: datalabels } },
                    heatmap: { dataLabels: { enabled: datalabels } },
                    line: { dataLabels: { enabled: datalabels }, marker: { enabled: false } },
                    pie: { dataLabels: { enabled: datalabels }, showInLegend: true },
                    polygon: { dataLabels: { enabled: datalabels } },
                    pyramid: { dataLabels: { enabled: datalabels } },
                    scatter: { dataLabels: { enabled: datalabels } },
                    series: { dataLabels: { enabled: datalabels } },
                    solidgauge: { dataLabels: { enabled: datalabels } },
                    spline: { dataLabels: { enabled: datalabels }, marker: { enabled: false } },
                    treemap: { dataLabels: { enabled: datalabels } },
                    waterfall: { dataLabels: { enabled: datalabels } }
                },
                'series': series,
                'tooltip': {
                    shared: false,
                    xDateFormat: '%d/%m/%Y',
                    pointFormat: '<span style="color:{series.color}">{series.name}</span>:<b>{point.y}</b><br/>'
                },
                'xAxis': {
                    'type': xDateType ? 'datetime' : 'linear',
                    'categories': xDateType ? null : [],
                    'dateTimeLabelFormats': { day: '%d/%m/%y', month: '%b/%Y', year: '%Y' },
                    'gridLineColor': '#fafafa',
                    'gridLineWidth': 1,
                },
                'yAxis': {
                    'title': { text: yTitle },
                    'gridLineColor': '#f0f0f0',
                    'gridLineWidth': 1,
                },
                'legend': {
                    'align': 'center',
                    'layout': 'horizontal',
                    'verticalAlign': 'bottom',
                    enabled: true,
                },
            });

            for (var i = 0; i < series.length; i++)
                if (series[i].hidden)
                    $(elementId).highcharts().series[i].hide();

            return isEmpty;
        };

        var _date = {
            toString: function (val) {
                var yyyy = val.getFullYear().toString();
                var mm = (val.getMonth() + 1).toString(); // getMonth() is zero-based
                var dd = val.getDate().toString();
                return (dd[1] ? dd : "0" + dd[0]) + '/' + (mm[1] ? mm : "0" + mm[0]) + '/' + yyyy; // padding
            },
            toStringFull: function (val) {
                var yyyy = val.getFullYear().toString();
                var MM = (val.getMonth() + 1).toString(); // getMonth() is zero-based
                var dd = val.getDate().toString();
                var hh = val.getHours().toString();
                var mm = val.getMinutes().toString();
                return (dd[1] ? dd : "0" + dd[0]) + '/' + (MM[1] ? MM : "0" + MM[0]) + '/' + yyyy + ' ' + (hh[1] ? hh : "0" + hh[0]) + ':' + (mm[1] ? mm : "0" + mm[0]); // padding
            }
        };

        return {
            buildChart: _buildChart,
            date: _date
        };
    }

})();

