var przyklad = {
    x: 5, 
    y: 2,
    matrix: [[1, 0.2, 0.3, 0.4, 0], [0.2, 0.4, 0.7, 0.9, 1]],
    columns: ['ula_count', 'ela_count', 'dla_count', 'cla_count', 'bla_count'],
    rows: [['plik 1', 'plik 2', 'plik 4', 'plik 5'], ['plik3']]
};
//ShowHeatMap(przyklad);

function ShowHeatMap(input)
{

    var data = input.data;
    var n1 = input.x;
    var n2 = input.y;


    var margin = {top: 180, right: 5, bottom: 9.5, left: 80.5},
    width = 1000,
            height = width / n1 * n2;

    matrix = input.matrix;


    var x = d3.scale.ordinal()
            .domain(d3.range(n1))
            .rangeBands([0, width]);

    var y = d3.scale.ordinal()
            .domain(d3.range(n2))
            .rangeBands([0, height]);

    var z = d3.scale.linear()
            .domain([1, 0.5, 0])
            .range(["red", "yellow", "blue"])
            .clamp(true);

    $('#chart').html("");
    var svg = d3.select("#chart").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .style("margin-left", 0 + "px")
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");




    svg.append("rect")
            .attr("class", "background")
            .attr("width", width)
            .attr("height", height);

    var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .html(function (d, i) {
                var html = "<strong><span lang='pl'>Elementy grupy</span><span lang='en'>Group elements</span>:</strong> <br><span style='color:red'>";
                for (j = 0; j < input.rows[i].length; j++)
                    html += input.rows[i][j] + '<br>';
                html += "</span>";
                return html;
            });

    svg.call(tip);

    var row = svg.selectAll(".row")
            .data(matrix)
            .enter().append("g")
            .attr("class", "row")
            .attr("transform", function (d, i) {
                return "translate(0," + x(i) + ")";
            });

    row.selectAll(".cell")
            .data(function (d) {
                return d;
            })
            .enter().append("rect")
            .attr("class", "cell")
            .attr("x", function (d, i) {
                return x(i);
            })
            .attr("width", x.rangeBand())
            .attr("height", y.rangeBand());

    row.append("line")
            .attr("x2", width);

    row.append("text")
            .attr("x", -6)
            .attr("y", y.rangeBand() / 2)
            .attr("dy", ".32em")
            .attr("text-anchor", "end")
            .text(function (d, i) {
                if (document.body.className == 'en')
                    return 'Group ' + (i + 1);
                //lang='en'
                return 'Grupa ' + (i + 1);
            })
            .on('mouseover', tip.show)
            .on('mouseout', tip.hide);

    var column = svg.selectAll(".column")
            .data(matrix[0])
            .enter().append("g")
            .attr("class", "column")
            .attr("transform", function (d, i) {
                return "translate(" + x(i) + ")rotate(-90)";
            });


    column.append("line")
            .attr("x1", -width);

    column.append("text")
            .attr("x", 6)
            .attr("y", x.rangeBand() / 2)
            .attr("dy", ".32em")
            .attr("text-anchor", "start")
            .text(function (d, i) {
                var row = input.columns[i].split(":");
                if (row[0] == 'lemma_count' || row[0] == 'orth_count')
                    row[1] = convert2PolishLetters(row[1]);
                return row[1];
            });

    row.selectAll(".cell")
            .data(function (d, i) {
                return matrix[i];
            })
            .style("fill", z)

}

$('#wyniki').hide();


//SET JSON options of specific activities in LPMN file
function NLP_SetOptions(engineString)
{
    engineString = engineString.replace("%cluto_content%", getClutoJSON());
    engineString = engineString.replace("%feature_options%", getFeatureJSON());
    return engineString;
}

//MAIN Function to show results
function NLP_ShowResults(out) {
    $('#wyniki').show();
    fileID = out[0]['fileID'];
    what = "/nlprest/base/downloadbin/" + fileID + "/descriptive_features.csv";
    $.get(what).done(function (data) {
        ShowCSV(data)
        NLP_ResultUploaded();
    }).fail(function (jqxhr, textStatus, er) {
        console.log(er)
    });

    what = "/nlprest/base/downloadbin/" + fileID + "/cluster_contents.csv";
    $.get(what).done(function (data) {
        ProcessClusterContents(data)
        NLP_ResultUploaded();
    }).fail(function (jqxhr, textStatus, er) {
        console.log(er)
    });

    what = "/nlprest/base/downloadbin/" + fileID + "/matrix.json";
    $.get(what).done(function (data) {
        ShowHeatMap(JSON.parse(data));
    }).fail(function (jqxhr, textStatus, er) {
        console.log(er)
    });



}



function getFeatureJSON() {
    var val = new Object();
    val['method'] = $('#selection_method').val();
    return JSON.stringify(val);
}


var resultcsv = null;
var cluster_content = null;
function save_click()
{
    SaveToDisk(resultcsv, 'result.csv', 'text/csv');
    if (cluster_content != null)
    {
        SaveToDisk(cluster_content, 'clusters.csv', 'text/csv');
    }
    else
    {
        console.log("Not yet loaded");
    }
}

function ProcessClusterContents(data)
{
    cluster_content = data;

}

function ShowGroup(id)
{
    var html = "";
    var rows = cluster_content.split("\n");
    for (row = 1; row < rows.length - 1; row++)
    {
        var ourrow = rows[row];
        var columns = ourrow.split(";");
        html += columns[id] + "<br>";

    }
    var len = columns.length;
    NLP_Alert("Infomacja na temat grupy: " + (id + 1), html);

}

function ShowCSV(data)
{
    resultcsv = data;
    var html = '<table id="csv">';
    html += '<thead><tr>';
    var rows = data.split("\n");
    var ourrow = rows[0];
    var columns = ourrow.split(";");
    var len = columns.length;
    html += '<th data-field="id0">ID&nbsp;</th>';
    for (var i = 0; i < len; i = i + 5)
        html += '<th data-field="id' + (i / 5 + 1) + '"  data-formatter="featureFormatter" >' +
                '<span lang="pl" data-toggle="tooltip" title="po naciśnięciu pojawi się lista składowa grupy"  onclick="ShowGroup(' + (i / 5) + ')">Grupa ' + (i / 5 + 1) + '</span>' +
                '<span lang="en" data-toggle="tooltip" title="click to see members"  onclick="ShowGroup(' + (i / 5) + ')">Group ' + (i / 5 + 1) + '</span>' +
                '</th>';

    html += '</tr></thead></table>';
    data1 = [];
    for (row = 2; row < rows.length - 1; row++)
    {
        var ourrow = rows[row];
        var columns = ourrow.split(";");
        var obj = {id0: row - 1};
        for (var i = 0; i < len; i = i + 5)
        {
            var tmp = columns[i];
            if (tmp !== 'undefined')
                obj['id' + (i / 5 + 1)] = tmp;
            else
                obj['id' + (i / 5 + 1)] = '&nbsp;';
        }
        data1[row - 2] = obj;
    }

    $('#result').html(html);
    $('#result_table').bootstrapTable('destroy');
    $('#csv').bootstrapTable({data: data1, height: 600, detailView: false});


}


function convertFeaturePrefix(value)
{
    var lang = $('body').attr('lang');
    if (lang = 'en')
    {
        if (value == 'lemma_count')
            return 'lemma';
        if (value == 'lexclass_count')
            return 'grammatical class';
        if (value == '2-gram_count')
            return 'bigram';
        if (value == '3-gram_count')
            return 'trigram';
        if (value == 'orth_count')
            return 'orth';
        if (value == 'interp_count')
            return 'punctuation mark';
    }
    else
    {
        if (value == 'lemma_count')
            return 'lemat';
        if (value == 'lexclass_count')
            return 'klasa gramtyczna';
        if (value == '2-gram_count')
            return 'bigram';
        if (value == '3-gram_count')
            return 'trójgram';
        if (value == 'orth_count')
            return 'orth';
        if (value == 'interp_count')
            return 'znak interpukcyjny';
    }
    return value;
}

String.prototype.replaceArray = function (find, replace) {
    var replaceString = this;
    var regex;
    for (var i = 0; i < find.length; i++) {
        regex = new RegExp(find[i], "g");
        replaceString = replaceString.replace(regex, replace[i]);
    }
    return replaceString;
};
function convert2PolishLetters(value)
{
    var find = ["o_", "a_", "s_", 'e_', 'n_', 'z_', 'e_', 'l_', 'c_'];
    var replace = ["ó", "ą", "ś", 'ę', 'ń', 'ż', 'ę', 'ł', 'ć'];
    return value.replaceArray(find, replace);
}
function featureFormatter(value) {
    if (value == "")
        return "";
    var row = value.split(":");
    if (row.length == 0)
        return "";
    if (row[0] == 'lemma_count' || row[0] == 'orth_count')
        row[1] = convert2PolishLetters(row[1]);
    return '<span data-toggle="tooltip" title="' + convertFeaturePrefix(row[0]) + '">' + row[1] + '</span>';
}



