var app = function () {

    var loader = $("#loader");
    var cluster_default_size = 9;
    var search_filter = $("#search-filter");
    var form_controller = $("#search-controller");
    var hidden_dcloud = $("#delta_cloud");
    var delta_cloud = $("#delta-could");
    var query_hidden_input = $("#query_values");
    var clusters_content = $("#clusters_content");
    var cluster_selector = $("#clusterSize");
    var top_items_section = $("#top_products_section");
    var aggs_list = {};
    var grp_aggr_selector = $('#grp_agg_content');
    var discipl_aggr_selector = $('#disp_agg_content');
    var author_aggr_selector = $('#author_agg_content');
    var publication_period = $('#publication_period');
    var keydiff = $("#keywordDiff");
    var enjoyhint_instance;

    var colors = ['rgba(255, 182, 193, .4)',
        'rgba(214, 208, 217, .4)',
        'rgba(21, 212, 9, .3)',
        'rgba(198, 41, 115, .3)',
        'rgba(249, 179, 94, .3)',
        'rgba(194, 194, 194, .3)',
        'rgba(188, 237, 239, .4)',
        'rgba(175, 201, 178, .4)',
        'rgba(188, 227, 239 , .4)',
        'rgba(224, 239, 188, .4)',
        'rgba(91, 117, 127, .3)',
        'rgba(198, 201, 175, .3)'];

    var charsController = function (size, filter) {
        jQuery.ajax('/v2/data',
            {
                data: {
                    "cluster_size": $('#clusterSize').find(":selected").text(),
                    "filter": filter,
                    "query": query_hidden_input.val(),
                    "cluster": query_hidden_input.attr("data-filter"),
                    "depth": query_hidden_input.attr("data-depth"),
                    "delta_cloud": hidden_dcloud.val(),
                    "grp_name": grp_aggr_selector.find(":selected").val(),
                    "disp_name": discipl_aggr_selector.find(":selected").val(),
                    "author_name": author_aggr_selector.find(":selected").val(),
                    "pub_period": publication_period.val()
                },
                dataType: 'json',
                success: function (data, status, xhr) {
                    loader.hide();
                    createCharts(data.result);
                },
                error: function (jqXhr, textStatus, errorMessage) { // error callback
                    console.log(errorMessage)
                }
            });
    };

    var facetsController = function (selected) {
        jQuery.ajax('/v2/facets',
            {
                data: {
                    "cluster_size": $('#clusterSize').find(":selected").text(),
                    "query": query_hidden_input.val(),
                    "grp_name": grp_aggr_selector.find(":selected").val(),
                    "disp_name": discipl_aggr_selector.find(":selected").val(),
                    "author_name": author_aggr_selector.find(":selected").val(),
                    "pub_period": publication_period.val()
                },
                dataType: 'json',
                success: function (data, status, xhr) {
                    buildFacet(data.result);
                },
                error: function (jqXhr, textStatus, errorMessage) { // error callback
                    console.log(errorMessage)
                }
            });
    };

    var buildFacet = function (data) {

        var disciplines = data.aggregations.discipline.buckets;
        var group_name = data.aggregations.group_name.buckets;
        var author = data.aggregations.author.buckets;

        var option = '<option value="" selected>Choose Group</option>';
        var selected = "";


        for (var index in disciplines) {
            if (!disciplines.hasOwnProperty(index)) continue;

            if (aggs_list["disp_agg_content"] === disciplines[index].key) {
                selected = "selected"
            }
            option += '<option value="' + disciplines[index].key + '"  ' + selected + '>' + disciplines[index].key + '</option>';
        }
        $("#disp_agg_content").html(option);


        option = '<option  value="" selected>Choose Discipline</option>';
        selected = "";
        for (index in group_name) {
            if (!group_name.hasOwnProperty(index)) continue;

            if (aggs_list["grp_agg_content"] === group_name[index].key) {
                selected = "selected"
            }
            option += '<option value="' + group_name[index].key + '" ' + selected + '>' + group_name[index].key + '</option>';
        }
        $("#grp_agg_content").html(option);


        option = '<option  value="" selected>Choose Author</option>';
        selected = "";
        for (index in author) {
            if (!author.hasOwnProperty(index)) continue;

            if (aggs_list["author_agg_content"] === author[index].key) {
                selected = "selected"
            }
            option += '<option value="' + author[index].key + '" ' + selected + '>' + author[index].key + '</option>';
        }
        author_aggr_selector.html(option)


    };


    var searchController = function () {

        var choices = new Choices('#search-input',
            {
                searchEnabled: true,
                maxItemCount: 10,
                removeItemButton: true,
                removeItems: true,
                silent: true,
                removeItem: function (item) {
                    console.log(item)
                }
            });

        choices.passedElement.addEventListener('addItem', function (event) {


            if (query_hidden_input.val().length > 0) {
                query_hidden_input.val(query_hidden_input.val() + "," + event.detail.value);
            } else {
                query_hidden_input.val(event.detail.value);
            }
            //form_controller.submit()
            reload_page();

        }, false);

        choices.passedElement.addEventListener('removeItem', function (event) {

            var values = query_hidden_input.val().split(",");
            var query = [];
            for (var element in values) {
                if (!values.hasOwnProperty(element)) continue;
                if (values[element] !== event.detail.value) {
                    query.push(values[element])
                }
            }
            query_hidden_input.val(query);
            reload_page();
        }, false);
    };

    var deltaCloudController = function () {
        if ($("#delta_cloud").val() === "true") {
            delta_cloud.attr("checked", true)
        } else {
            delta_cloud.attr("checked", false)
        }

        delta_cloud.change(function () {
            if ($(this).is(":checked")) {
                hidden_dcloud.val(true);
            } else {
                hidden_dcloud.val(false);
            }
            form_controller.submit();
        });
    };

    var createCharts = function (result) {

        if (typeof result === 'undefined') {
            //emptyResult();

        }

        var traces = [];


        for (var e in result) {
            traces.push({
                x: result[e].X,
                y: result[e].Y,
                text: result[e].TEXT,
                hovertext: result[e].HOVERS,
                freeText: result[e].IDS,
                name: 'Cluster ' + e,
                mode: 'markers+text',
                marker: {
                    size: 14, line: {
                        width: 1,
                        color: 'rgba(0, 0, 0, .1)'
                    },
                    color: colors[e]
                },
                type: 'scatter'
            });
        }

        Plotly.newPlot('clusters_content', traces, {
            showlegend: true,
            height: 910,
            yaxis: {
                showline: false,
                showgrid: true,
                zeroline: false,
                autorange: true,
                showticklabels: false,
                ticks: ''
            },
            xaxis: {
                showline: false,
                showgrid: false,
                zeroline: false,
                autorange: true,
                showticklabels: false,
                ticks: ''
            },
            font: {
                color: '#000',
                size: 18
            }
        });

        document.getElementById('clusters_content').on('plotly_click', function (d) {
            var id = d.points[0].hovertext.split("<i style='display:none'>")[1].replace("</i>", "");
            window.open("/doc?id=" + id, "_blank");
        });
    };


    var topDocumentController = function (filter, main_filter) {
        jQuery.ajax('/v2/top_items',
            {
                data: {
                    "query": query_hidden_input.val(),
                    "cluster_size": cluster_selector.find(":selected").val(),
                    "grp_name": grp_aggr_selector.find(":selected").val(),
                    "disp_name": discipl_aggr_selector.find(":selected").val(),
                    "author_name": author_aggr_selector.find(":selected").val(),
                    "pub_period": publication_period.val()
                },
                dataType: 'json',
                success: function (result) {
                    var colors_counter = 1;
                    var top_items = "";
                    for (var resp in result) {
                        if (!result.hasOwnProperty(resp)) continue;

                        var tmp = result[resp];
                        if (tmp["total"] > 0) {
                            top_items = top_items + "<h6 class='top_title' style='background-color: " + colors[colors_counter] + "'><a data-toggle='tooltip' data-placement='top' title='Cluster " + (parseInt(resp) + 1) + "'>Cluster " + (parseInt(resp) + 1) + "</a><span class='total'> Total: " + tmp["total"] + "</span></h6>";
                            colors_counter++;
                        }
                        var counter = 0;
                        for (var doc in tmp['docs']) {
                            if (!tmp['docs'].hasOwnProperty(doc)) continue;
                            var item = tmp['docs'][doc];
                            counter++;
                            if (counter < 5) {
                                top_items = top_items + "<div class='top_item'><a target='_blank' class='top_item_link' href='/doc?id=" + item["id"] + "'>" + item["title"].substr(0, 60) + "...</a></div>"

                            }
                        }
                    }
                    top_items_section.html(top_items);
                    //re-render the tooltip
                    $('[data-toggle="tooltip"]').tooltip()
                },
                error: function (jqXhr, textStatus, errorMessage) {
                    console.log(errorMessage)
                }
            });
    };

    var clusterController = function () {
        $("#grp_agg_content, #clusterSize, #disp_agg_content, #author_agg_content").on("change", function () {
            aggs_list[$(this).attr("id")] = $(this).val();
            reload_page();
        });
    };

    var reload_page = function () {
        loader.show();
        charsController();
        facetsController();
        topDocumentController();
    };

    var publicationPeriod = function () {
        publication_period.on("click", function () {
            reload_page();
        })
        publication_period.daterangepicker({
            opens: 'right',
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function (start, end) {
            publication_period.val(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
            reload_page();
        });

        publication_period.on('cancel.daterangepicker', function (ev, picker) {
            $(this).val('');
            reload_page();
        });
    };

    var clearBtn = function () {
        $("#clean_authr").on("click", function (e) {
            e.preventDefault();
            author_aggr_selector.find("option:selected").removeAttr('selected');
            author_aggr_selector.find('option:eq(0)').attr("selected", "selected").change();
        });
        $("#clean_disc").on("click", function (e) {
            e.preventDefault();
            discipl_aggr_selector.find("option:selected").removeAttr('selected');
            discipl_aggr_selector.find('option:eq(0)').attr("selected", "selected").change();
        });

        $("#clean_grp").on("click", function (e) {
            e.preventDefault();
            grp_aggr_selector.find("option:selected").removeAttr('selected');
            grp_aggr_selector.find('option:eq(0)').attr("selected", "selected").change();
        });

        $("#clean_ukey").on("click", function (e) {
            e.preventDefault();
            keydiff.find("option:selected").removeAttr('selected');
            keydiff.find('option:eq(0)').attr("selected", "selected").change();
        });


    };


    var emptyResult = function () {
        clusters_content.html("<div>No result found for your request.</div>")
    };


    var tour = function () {
        enjoyhint_instance = new EnjoyHint({});
        var enjoyhint_script_steps = [
            {'next #clusterSize': 'Choose the number of clusters you like to start with'},
            {
                'next #clusterparent': 'The result is showed in the word cloud',
                "nextButton": {className: "hoverNext", text: "NEXT"},
                "skipButton": {className: "hoverNext", text: "SKIP"}
            },
            {
                'next .legend': "Double click on the legend name to navigate inside the cluster",
                'shape': 'circle',
                'radius': 80
            },
            {
                'next .legend': "Or just click on the legend of a cluster to hide its data",
                'shape': 'circle',
                'radius': 80
            },
            {'next #searchKW': 'Search for documents inside the clusters using a keyword'},
            {'next .top_products': 'The top products of your query will be showed here'},
            {'next .top_title': 'The top products of the first cluster'},
            {'next .total': 'Total number of documents based on your query'},
            {'next #publication_period': "Use this element to filter the documents by a publication period"},
            {'next #grp_agg_content': "Or filter the result by a group"},
            {'next .clearBtn': "Clear the filter if you no document is found"},
            {'next #disp_agg_content': "You can also select documents from a discipline"},
            {'next #author_agg_content': "Or filter the result by an author"}
        ];

        enjoyhint_instance.set(enjoyhint_script_steps);
        enjoyhint_instance.run();
    };

    return {
        run: function () {
            charsController(cluster_default_size, search_filter.val());
            clusterController();
            searchController();
            deltaCloudController();
            createCharts();
            topDocumentController(search_filter.val());
            facetsController();
            publicationPeriod();
            clearBtn();
            tour();
            $('[data-toggle="tooltip"]').tooltip()
        }
    };

}();