/*!
 * jQuery Easy Charts
 * http://easyredmine.com/
 *
 * Copyright 2015 Easy Software Ltd.
 */
//= require_self


(function( $, undefined ) {

  $.widget("easy.easy_chart", {
    defaultColors: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd',
      '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'],
    defaultSpace: 20,
    colors: function (){
      if (ERUI.sassData !== undefined && ERUI.sassData['chart-palette']){
        return ERUI.sassData['chart-palette'].split(",");
      }else{
        return this.defaultColors;
      }

    },
    space: function (){
      if (ERUI.sassData !== undefined && ERUI.sassData['base-spaceing']){
        return ERUI.sassData['base-spacing'].split("px")[0];
      }else{
        return this.defaultSpace;
      }

    },
    i18n: {
      noData: 'No data',
      currentData: 'Current',
      createBaseline: 'Create baseline',
      loadBaseline: 'Load',
      toggleBaseline: 'Baseline'
    },
    localeDefinition: {
      "decimal": ".",
      "thousands": ",",
      "grouping": [3],
      "currency": ["$", ""],
      "dateTime": "%a %b %e %X %Y",
      "date": "%m/%d/%Y",
      "time": "%H:%M:%S",
      "periods": ["AM", "PM"],
      "days": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
      "shortDays": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
      "months": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      "shortMonths": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    },
    options: {
      blockName: null, // block_name of chart area
      dataUrl: null, // url to make a request for data to
      dataParams: {}, // params to pass to ajax
      reloadRate: 0,
      defaultChartOptions: {},
      formats: { labels: ",", y_axis: "," },
      currency: null
    },

    _create: function() {
      this.uuid = this.element.data('uuid');
      this.options.dataParams = $.extend({uuid: this.uuid}, this.options.dataParams)
      this.options.dataUrl = this.options.dataUrl || this.element.data('url');

      this.chart_data = null;
      this.currency = this.options.currency || [this.element.data('currency-prefix') || '', this.element.data('currency-suffix') || ''];

      if( this.element.data('renderchart') ) {
        this._loadAndCreate(false);
      }

      if( this.uuid !== undefined && this.uuid ) {
        this._createBaselines();
      }
    },

    _loadAndCreate: function(replot) {
      var that = this;
      $.ajax({
        url: this.options.dataUrl,
        data: this.options.dataParams,
        noLoader: true,
        dataType: "json", type: "GET"
      }).done(function (data) {
        var title = $('.chart-title-' + that.uuid);
        if (title !== undefined){
          title.text(data.title);
        }
        if ( (data.data.columns !== undefined && (data.data.columns.length === 0 || data.data.columns[0].length === 0)) || (data.data.json !== undefined && data.data.json.length === 0) ) {
          that.element.html(that.i18n.noData);
        } else {
          that._configureAndCreateChart(data);
        }
      });
    },

    _createBaselines: function() {
      var that = this,
          create_button, toggle_button, load_button,
          heading_links = this.element.closest('.easy-page-module').find('.module-heading-links');

      this.baseline_container = $('<div class="baseline_container" style="display:none;"></div>');
      this.baseline_select = $('<select/>').appendTo( this.baseline_container );
      load_button = $('<a href="javascript:void(0)" class="button-2">' + this.i18n.loadBaseline + '</a>').appendTo( this.baseline_container );
      create_button = $('<a href="javascript:void(0)" class="button-1">' + this.i18n.createBaseline + '</a>').appendTo( this.baseline_container );
      toggle_button = heading_links.find('.baseline-toggle'); // for second load - change of period
      if( toggle_button.length === 0 ) {
        toggle_button = $('<a href="javascript:void(0)" class="icon icon-lightning baseline-toggle" title="'+ this.i18n.toggleBaseline + '"></a>');
        heading_links.prepend( toggle_button );
      } else {
        toggle_button.off('click');
      }

      toggle_button.on('click', function(evt) {
        that._loadBaselines();
        that.baseline_container.toggle();
      });

      create_button.on('click', function(evt) {
        evt.preventDefault();
        that._saveBaseline();
      });

      load_button.on('click', function(evt) {
        evt.preventDefault();
        if( that.baseline_select.val() ) {
          that._loadBaseline( that.baseline_select.val() );
        } else {
          that.reload();
        }
      });

      this.element.before( this.baseline_container );
    },

    _configureAndCreateChart: function(chartData) {
      if (chartData === null) {
        return null;
      }

      var that = this,
          default_number_format,
          currency,
          formatDefaults,
          label_format,
          total_text,
          locale,
          localeDefinition,
          countProps,
          chartAdditionalOptions = {};

      // var chart_size = [300, 300];
      currency = chartData.currency || this.currency;
      localeDefinition = $.extend( {}, this.localeDefinition, {'currency': currency});
      if( chartData.formats && chartData.formats.delimiter ) {
        localeDefinition.thousands = chartData.formats.delimiter
      }
      if( chartData.formats && chartData.formats.separator ) {
        localeDefinition.decimal = chartData.formats.separator
      }
      locale = d3.locale( localeDefinition );
      default_number_format = locale.numberFormat(',');
      formatDefaults = {
        currency: locale.numberFormat('$,'),
        time: function(d) { return default_number_format(d) + 'h'; }
      };

      this.chart_data = chartData;
      this.chart_type = chartData.data.type;
      this.has_more_series = (chartData.data.columns !== undefined && chartData.data.columns.length > 1);
      this.has_more_series = this.has_more_series || (chartData.data.keys !== undefined && chartData.data.keys.value.length > 1);

      this.formats = $.extend( {}, this.options.formats, chartData.formats );

      label_format =  formatDefaults[this.formats.labels] || locale.numberFormat(this.formats.labels)

      $.extend(true, chartAdditionalOptions, {
        data: {
          labels: {
            format: label_format
          }
        }
      });

      if( this.chart_type != 'pie' && !this.has_more_series ) {
        $.extend(true, chartAdditionalOptions, {
          legend: {
            show: false
          }
        });
      }
      if( this.chart_type == 'bar' && !this.has_more_series ) {
        $.extend(true, chartAdditionalOptions, {
          data: {
            color: function (color, d) {
              return that.colors()[d.index % that.colors().length];
            }
          },
          size: {
             height: function () {
                 if (that.chart_options.axis.rotated){
                     return that.chart_data.data.json.length*this.space;
                 }
             }
          }
        });
      } else {
        $.extend(true, chartAdditionalOptions, {
          color: {
            pattern: that.colors()
          }
        });
      }
      if( this.chart_type == 'pie' ) {
        $.extend(true, chartAdditionalOptions, {
          tooltip: {
            format: {
              value: function(value, ratio, id) {
                return d3.format(".0%")(ratio) + ' (' + label_format(value) + ')';
              }
            }
          }
        });
      }

      if( chartData.total !== undefined ) {
        if ( $.isPlainObject(chartData.total) ) {
          total_text = '';
          countProps = 0;
          for ( var k in chartData.total ) {
            if (countProps > 0) {
              total_text += ' | ';
            }
            total_text += ( chartData.data.names[k] || "Total"+(i+1).toString() ) + ": " + label_format(chartData.total[k]);
            countProps++;
          }
        } else {
          total_text = "Total: " + label_format(chartData.total)
        }
      }

      this.chart_ticks = chartData.ticks;
      this.chart_options = $.extend(true, {
        bindto: this.element.get(0),
        data: chartData.data,
        title: {
          text: total_text
        },
        padding: {
          top: that.space(),
          bottom: 1.5*that.space(),
        },
        axis: {
          x: {
            type: 'category',
            /*tick: {
              rotate: 30
            },*/
            categories: this.chart_ticks,
            height: 30
          },
          y: {
            tick: {
              format: formatDefaults[this.formats.y_axis] || locale.numberFormat(this.formats.y_axis)
            },
            padding: {
              top: 0.1,
              bottom: 0.1,
              unit: 'ratio'
            }
          }
        },
        grid: {
          y: {
            show: true
          }
        },
        line: {
          connectNull: true
        }
      }, this.options.defaultChartOptions, chartAdditionalOptions, chartData.chart_options);

      if( this.chart_type == 'bar' && this.chart_options.axis.rotated ) {
        if (this.chart_options.size) {
          this.chart_options.size.height = (this.chart_data.data.json.length + 1) * this.chart_options.axis.x.height;
        }
        this.element.addClass('is-rotated');
      }

      this.chart = c3.generate(this.chart_options);

      return this.chart;
    },

    _loadBaselines: function() {
      var that = this;
      this.baseline_select.children().remove();
      $.ajax(window.urlPrefix + '/easy_page_zone_modules/'+this.uuid+'/easy_chart_baselines.json').done(function(data) {
        that.baseline_select.append('<option value="">' + that.i18n.currentData + '</option>');
        for (var i = 0; i < data.length; ++i) {
          that.baseline_select.append('<option value="'+data[i].id.toString() + '">' + (data[i].name || 'No name') + ' (' + data[i].date + ')</option>');
        }
      });
    },

    _saveBaseline: function() {
      $.ajax(window.urlPrefix + '/easy_page_zone_modules/'+this.uuid+'/easy_chart_baselines.json', {
        method: 'POST',
        data: {
          easy_chart_baseline: {
            data: this.chart_data.data,
            ticks: this.chart_ticks,
            options: this.chart_data.chart_options
          }
        }
      });
    },

    _loadBaseline: function( baseline_id ) {
      var that = this;
      $.ajax(window.urlPrefix + '/easy_chart_baselines/'+baseline_id.toString()+'.json').done(function(data) {
        // var columns;
        // for( var key in data.data.columns) {
        //   columns = data.data.columns[key];
        //   break;
        // }
        // columns.shift();
        // columns = columns.map(parseFloat);
        // columns.unshift( 'Baseline ' + data.date );
        that._configureAndCreateChart(data);
      });
    },

    reload: function() {
      this.chart = this.chart.destroy();
      this._loadAndCreate(true);
    },

    setDataParam: function(param, value) {
      this.options.dataParams[param] = value;
    },

    getDataParam: function(param) {
      return this.options.dataParams[param];
    },

  });

})( jQuery );
