var app = function () {

    var loader = $("#loader");
    var cluster_default_size = 3;
    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");
    const DOCUMENT_PAGE = "/docs";
    var cluster_selector = $("#clusterSize");
    var top_items_section = $("#top_products_section");


    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('/data',
            {
                data: {
                    "cluster_size": size,
                    "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()
                },
                dataType: 'json',
                success: function (data, status, xhr) {
                    loader.hide();
                    createCharts(data.result);
                },
                error: function (jqXhr, textStatus, errorMessage) { // error callback
                    console.log(errorMessage)
                }
            });
    };


    var clusterController = function () {
        $("#clusterSize").on("change", function () {
            charsController(this.value);
        })
    };

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

        }, 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);
            form_controller.submit()
        }, 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;

            var display = "none";
            var url = DOCUMENT_PAGE + window.location.search + "&name=" + result[cluster]["name"] + "&cluster_size=" + clustersize;
            if (parseInt(result[cluster]["total"]) < 2 || result[cluster]["feature"].length === 0) {
                display = "block";
            }
            clsname.push(result[cluster]["name"]);
            html_content += "<div class='cluster' ><h5>" + result[cluster]["name"] + "<span class='cluster_sz'>(" + result[cluster]["total"] + " document)</span><span class='show_document' style='display: " + display + "'><a target='_blank' href='" + url + "' class='btn btn-info' ><i class='fas fa-file-invoice'></i></a></span></h5><div id='chart_" + cluster + "' class='chart-area' /></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
                }
            });
        }

        tree = "";
        for (var cls = 0; cls < clustersize; cls++) {
            var ul_subc = "";
            if (cls == query_hidden_input.attr("data-filter")) {
                var tb = "";
                for (var name in clsname) {
                    tb = tb + "<li>" + clsname[name].split(";")[0].substring(0, 30) + "</li>"
                }
                ul_subc = "<ul>" + tb + "</ul>"
            }
            tree = tree + "<li> Cluster " + (cls + 1) + ul_subc + "</li>"
        }
        $("#tree").html(tree)
    };


    var topDocumentController = function (filter, main_filter) {
        jQuery.ajax('/top_items',
            {
                data: {
                    "filter": filter,
                    "main_filter": main_filter,
                    "query": query_hidden_input.val(),
                    "cluster_size": cluster_selector.find(":selected").val()
                },
                dataType: 'json',
                success: function (result) {
                    var top_items = "";
                    var titles = [];
                    for (var resp in result.responses) {
                        if (!result.responses.hasOwnProperty(resp)) continue;
                        var tmp = result.responses[resp];
                        var counter = 0;
                        for (var doc in tmp['hits']['hits']) {
                            counter++;
                            if (counter < 5) {
                                top_items = top_items + "<div class='top_item'><a target='_blank' class='top_item_link' href='/doc?id=" + tmp['hits']['hits'][doc]["_id"] + "'>" + tmp['hits']['hits'][doc]["_source"]["title"] + "</a></div>"

                            }
                        }
                    }
                    top_items_section.html(top_items)
                },
                error: function (jqXhr, textStatus, errorMessage) {
                    console.log(errorMessage)
                }
            });
    };


    return {
        run: function () {
            charsController(cluster_default_size, search_filter.val());
            clusterController();
            searchController();
            deltaCloudController();
            createCharts();
            topDocumentController(search_filter.val());
        }
    };

}();