odoo.define('kpi.widget', function (require) {
"use strict";

var core = require('web.core');
var kanban_widgets = require('web_kanban.widgets');
var utils = require('web.utils');

var AbstractField = kanban_widgets.AbstractField;
var fields_registry = kanban_widgets.registry;
var _t = core._t;
var mean=0.5

/**
 * Kanban widgets: GaugeWidget
 * options
 * - max_value: maximum value of the gauge [default: 100]
 * - max_field: get the max_value from the field that must be present in the
 *              view; takes over max_value
 * - gauge_value_field: if set, the value displayed below the gauge is taken
                        from this field instead of the base field used for
                        the gauge. This allows to display a number different
                        from the gauge.
 * - force_set: is value is 0, display a text 'Click to set' [default: True]
 * - label: lable of the gauge, displayed below the gauge value
 * - title: title of the gauge, displayed on top of the gauge
 * - on_change: action to call when cliking and setting a value
 * - on_click_label: optional label of the input displayed when clicking
 *
 */

var GaugeWidget = AbstractField.extend({
    className: "oe_gauge",

    start: function() {
        var self = this;
        var parent = this.getParent();
        // parameters
        var max_value = this.options.max_value || 100;
        var min_value = this.options.min_field || 0;
        var polarity = this.options.polarity_field || 1;
        
        if (this.options.max_field) {
            max_value = this.getParent().record[this.options.max_field].raw_value;
        }
        if (this.options.min_field) {
            min_value = this.getParent().record[this.options.min_field].raw_value;
        }
        if (this.options.polarity_field) {
            polarity = this.getParent().record[this.options.polarity_field].raw_value || 1;
        }
        
        var label = this.options.label || "";
        if (this.options.label_field) {
            label = this.getParent().record[this.options.label_field].raw_value;
        }
        var polarity_label=polarity > 0 ? "( + )" : "( - )"
        var title = (this.$node.html() || this.field.string)+" "+polarity_label;
        // current gauge value
        var val = this.field.raw_value;
        
      
        var value = _.isArray(val) && val.length ? val[val.length-1]['value'] : val;
        
        // displayed value under gauge
        var gauge_value = value;

        var degree = Math.PI/180,
            width = 200,
            height = 150,
            outerRadius = Math.min(width, height)*0.5,
            innerRadius = outerRadius*0.7,
            fontSize = height/7;

        this.$el.empty().attr('style', this.$node.attr('style') + ';position:relative; display:inline-block;');

        var arc = d3.svg.arc()
                .innerRadius(innerRadius)
                .outerRadius(outerRadius)
                .startAngle(-90*degree);

        var svg = d3.select(this.$el[0])
            .append("svg")
            .attr("width", '100%')
            .attr("height", '100%')
            .attr('viewBox','0 0 '+width +' '+height )
            .attr('preserveAspectRatio','xMinYMin')
            .append("g")
            .attr("transform", "translate(139,126)");

        function addText(text, fontSize, dx, dy) {
            return svg.append("text")
                .attr("text-anchor", "middle")
                .style("font-size", fontSize+'px')
                .attr("dy", dy)
                .attr("dx", dx)
                .text(text);
        }
        // top title

        addText(title, 14, 0, -outerRadius-16).style("font-weight",'bold');

        // center value

        var text = addText(value, fontSize, 0, -2).style("font-weight",'bold');

        // bottom label

        addText(min_value, 11, -(outerRadius+innerRadius)/2, 12);
        addText(label, 8, 0, 12);
        addText(max_value, 11, (outerRadius+innerRadius)/2, 12);

        // chart

        svg.append("path")
            .datum({endAngle: Math.PI/2})
            .style("fill", "#ddd")
            .attr("d", arc);

        max_value=min_value<0 ? max_value-min_value : max_value;
        var ratio =max_value ? (value-min_value)/max_value : 0;
        var ratio_polarity=Math.round((mean-(polarity*(mean-ratio)))*100)/100
        var hue = Math.round(ratio_polarity*120);

        var foreground = svg.append("path")
            .datum({endAngle: (ratio-0.5)*Math.PI})
            .style("fill", "hsl(" + hue + ",80%,50%)")
            .attr("d", arc);
    },
});

fields_registry.add("kpi_gauge", GaugeWidget);

});
