odoo.define('survey.result', function (require) {
'use strict';

require('web.dom_ready');

if(!$('.js_surveyresult').length) {
    return $.Deferred().reject("DOM doesn't contain '.js_surveyresult'");
}

    //Script For Pagination
    var survey_pagination = $('.pagination');
    $.each(survey_pagination, function(index, pagination){
        var question_id = $(pagination).attr("data-question_id");
        var limit = $(pagination).attr("data-record_limit"); //Number of Record Par Page. If you want to change number of record per page, change record_limit in pagination template.
        $('#table_question_'+ question_id +' tbody tr:lt('+limit+')').removeClass('d-none');
        $('#pagination_'+question_id+' li a').click(function(event){
            event.preventDefault();
            $('#pagination_'+question_id+' li').removeClass('active');
            $(this).parent('li').addClass('active');
            $('#table_question_'+ question_id +' tbody tr').addClass('d-none');
            var num = $(this).text();
            var min = (limit * (num-1))-1;
            if (min == -1){
                $('#table_question_'+ question_id +' tbody tr:lt('+ limit * num +')').removeClass('d-none');
            }
            else{
                $('#table_question_'+question_id+' tbody tr:lt('+ limit * num +'):gt('+min+')').removeClass('d-none');
            }
        });
        $('#pagination_'+question_id+' li:first').addClass('active').find('a').click();
    });

    //initialize MultiBar Chart
    function init_multibar_chart(){
        var chart = nv.models.multiBarChart()
            .x(function(d) { return d.text; })
            .y(function(d) { return d.count; })
            .staggerLabels(true);

        // Replacing Library's Default Tooltip with our Custom One
        chart.tooltip(function(key, x, y, e) {
            return '<h5 class="bg-primary text-white"><div class="card-header">' + x + '</div></h5>' +
            '<p>' + '<b>Responses : </b>' + key + '</p>' +
            '<p>' + "<b>Total Vote : </b>" + y + '</p>';
        });
        return chart;
    }

    //initialize discreteBar Chart
    function init_bar_chart(){
        var chart = nv.models.discreteBarChart()
            .x(function(d) { return d.text; })
            .y(function(d) { return d.count; })
            .staggerLabels(true)
            .showValues(true);

        chart.tooltip.enabled(false);
        return chart;
    }

    //initialize Pie Chart
    function init_pie_chart(){
        return nv.models.pieChart()
            .x(function(d) { return d.text; })
            .y(function(d) { return d.count; })
            .showLabels(false);
    }

    //load chart to svg element chart:initialized chart, response:AJAX response, quistion_id:if of survey question, tick_limit:text length limit
    function load_chart(chart, response, svgSelector, tick_limit, graph_type){
        // Custom Tick fuction for replacing long text with '...'
        var customtick_function = function(d){
            if(! this || d.length <= tick_limit){
                return d;
            }
            else{
                return d.slice(0,tick_limit) + '...';
            }
        };
        if (graph_type != 'pie'){
            chart.xAxis
                .tickFormat(customtick_function);
            chart.yAxis
                .tickFormat(d3.format('d'));
        }
        d3.select(svgSelector)
            .datum(response)
            .transition().duration(500).call(chart);
        nv.utils.windowResize(chart.update);
        return chart;
    }
    //Script For Graph
    var survey_graphs = $('.survey_graph');
    $.each(survey_graphs, function(index, graph){
        var question_id = $(graph).attr("data-question_id");
        var graph_type = $(graph).attr("data-graph_type");
        var graph_data = JSON.parse($(graph).attr("graph-data"));
        var svgSelector = '#graph_question_' + question_id + ' svg';
        if(graph_type == 'multi_bar'){
            nv.addGraph(function(){
                var chart = init_multibar_chart();
                return load_chart(chart, graph_data, svgSelector, 25);
            });
        }
        else if(graph_type == 'bar'){
            nv.addGraph(function() {
                var chart = init_bar_chart();
                return load_chart(chart, graph_data, svgSelector, 35);
            });
        }
        else if(graph_type == 'pie'){
            nv.addGraph(function() {
                var chart = init_pie_chart();
                return load_chart(chart, graph_data, svgSelector, 25, 'pie');
            });
        }
    });

    var $scoringResultsChart = $('#scoring_results_chart');
    if ($scoringResultsChart.length > 0) {
        nv.addGraph(function () {
            var chart = init_pie_chart();
            return load_chart(chart, $scoringResultsChart.data('graph_data'), '#scoring_results_chart svg', 25, 'pie');
        });
    }

    // Script for filter
    $('td.survey_answer').hover(function(){
        $(this).find('i.fa-filter').removeClass('invisible');
    }, function(){
        $(this).find('i.fa-filter').addClass('invisible');
    });
    $('td.survey_answer i.fa-filter').click(function(){
        var cell = $(this);
        var row_id = cell.attr('data-row_id') | 0;
        var answer_id = cell.attr('data-answer_id');
        if(document.URL.indexOf("?") == -1){
            window.location.href = document.URL + '?' + encodeURI(row_id + ',' + answer_id);
        }
        else {
            window.location.href = document.URL + '&' + encodeURI(row_id + ',' + answer_id);
        }
    });

    // for clear all filters
    $('.clear_survey_filter').click(function(){
        window.location.href = document.URL.substring(0,document.URL.indexOf("?"));
    });
    $('span.filter-all').click(function(){
        event.preventDefault();
        if(document.URL.indexOf("finished") != -1){
            window.location.href = document.URL.replace('?finished&','?').replace('&finished&','&').replace('?finished','').replace('&finished','');
        }
    }).hover(function(){
        if(document.URL.indexOf("finished") == -1){
            $(this)[0].style.cursor = 'default';
        }
    });
    // toggle finished/all surveys filter
    $('span.filter-finished').click(function(){
        event.preventDefault();
        if(document.URL.indexOf("?") == -1){
            window.location.href = document.URL + '?' + encodeURI('finished');
        }
        else if(document.URL.indexOf("finished") == -1){
            window.location.href = document.URL + '&' + encodeURI('finished');
        }
    }).hover(function(){
        if(document.URL.indexOf("finished") != -1){
            $(this)[0].style.cursor = 'default';
        }
    });

});
