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");
    const DOCUMENT_PAGE = "/doc?id=";
    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 choices;
    var enjoyhint_instance;

    function getRandomColor(step) {
        var letters = '123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }


    var charsController = function (size, filter) {
        jQuery.ajax('/v3/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(),
                    "uniq_keys": keydiff.find(":selected").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('/v3/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) {

        if (data.hits.total === 0) {
            emptyResult();
            return
        }

        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 () {

        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);
            }
            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) {
        var html_content = "";
        var clsname = [];
        var clustersize = cluster_selector.find(":selected").val();
        for (var cluster in result) {
            if (!result.hasOwnProperty(cluster)) continue;
            if (result[cluster]["total"] === 0) continue;
            var display = "none";

            var url = DOCUMENT_PAGE + window.location.search + "&name=" + result[cluster]["name"] + "&cluster_size=" + clustersize;
            if (parseInt(result[cluster]["total"]) < 2) {
                display = "block";
            }
            clsname.push(result[cluster]["name"]);
            html_content += "<div class='cluster row' ><div class='col-md-9 wordkd'><h5>" + result[cluster]["name"] + "<span class='cluster_sz'>Total: " + result[cluster]["total"] + "</span><span class='show_document' style='display: " + display + "'></span></h5><div id='chart_" + cluster + "' class='chart-area' /></div><div class='col-md-3 top_product_cluster' id='top_cluster_" + cluster + "'></div></div>";
        }
        clusters_content.html(html_content);

        for (cluster in result) {
            if (!result.hasOwnProperty(cluster)) continue;


            $('#chart_' + cluster).empty().jQCloud(result[cluster]["feature"], {
                height: 300,
                steps: 20,
                autoResize: true,
                delay: 2,
                colors: function (step) {
                    return getRandomColor(step)
                },
                fontSize: {
                    from: 0.1,
                    to: 0.02
                }
            });
        }
    };


    var topDocumentController = function (filter, main_filter) {
        jQuery.ajax('/v3/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 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>Top products</h6>";
                        }
                        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_v3'><a target='_blank' class='top_item_link' href='/doc?id=" + item["id"] + "'>" + item["title"].substr(0, 60) + "...</a></div>"

                            }
                        }
                        $("#top_cluster_" + (resp)).html(top_items)
                        top_items = ""
                    }
                },
                error: function (jqXhr, textStatus, errorMessage) {
                    console.log(errorMessage)
                }
            });
    };

    var clusterController = function () {
        $("#grp_agg_content, #clusterSize, #disp_agg_content, #author_agg_content, #keywordDiff").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 cloudLinks = function () {
        $(document).on("click", ".jqcloud-word > a", function (e) {
            e.preventDefault();
            choices.setValue([$(this).get(0).innerHTML])
            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 .wordkd': 'The result is categorized in clusters and showed as word cloud',
                "nextButton": {className: "hoverNext", text: "NEXT"},
                "skipButton": {className: "hoverNext", text: "SKIP"}
            },
            {'next #searchKW': 'Search for documents inside the clusters using a keyword'},
            {'next .w1': 'Or you can even click on a word from a cloud'},
            {'next .top_product_cluster': 'The top products of your query will be showed here'},
            {'next .cluster_sz': 'Total number of documents based on your query'},
            {'next #keywordDiff': "Show words that appear only once in each cloud"},
            {'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();
            cloudLinks();
            clearBtn();
             tour();
            $('[data-toggle="tooltip"]').tooltip()
        }
    };

}();