var commentsInfo
var tsvString
var stopwords = ["妳", "的", "是", "在", "卻", "也", "了", "而", "要", "啊", "阿", "又", "有", "不", "我", "都", "就", "會", "完整", "新聞", "標題", "內文", "之", "你", "還", "人", "嗎", "沒", "跟", "說", "他", "我", "在", "被", "可以", "請", "來", "但", "沒有", "就是", "想", "讓", "自己", "對", "去", "到", "這", "大家", "才", "我們", "好", "用", "過", "啦", "後", "知道", "做", "很", "上", "她", "短", "網址", "備註", "連結", "或", "已", "把", "那", "只", "所以", "講"]
var url = [
    'https://www.dcard.tw/f/mood/p/234367759',
    'https://www.dcard.tw/f/relationship/p/234367304',
    'https://www.dcard.tw/f/trending/p/234366829'
]
init()

function init() {
    $(window).on('mousemove', function(e) {
        $('#nodeTitle').css({
            left: e.pageX,
            top: e.pageY
        })
    })
    changeData(1)
    $('#idfEditorLayer').click(function(e) {
        if ($('#idfEditorLayer').is(e.target)) {
            hideIdfEditor()
        }
    })
}

function scrollIdfList() {
    let targetWord = $('#idfTarget').val()
    let wordList = $("#ieContainer").find("tr").slice(1).map((_, a) => { return $($(a).find("td")[0]).html() }).get()
    console.log({ "targetWord": targetWord, 'list': wordList })
    if (targetWord != '') {
        if (wordList.indexOf(targetWord) >= 0) {

        } else {
            wordList.push(targetWord)
            $('#ieContainer').find('tbody').append($('<tr>').attr('class', 'w3-display-container').append($('<td>').attr('style', 'vertical-align: middle;').append(targetWord)).append($('<td>').attr('class', 'w3-right-align').attr('style', 'vertical-align: middle;').append($('<input>').attr('type', 'number').val(Object.keys(idfTable).indexOf(targetWord) < 0 ? 0 : idfTable[targetWord]))))
        }
        console.log($($('#ieContainer').children('tbody').find('tr')[[wordList.indexOf(targetWord)]]).position())
        $("#ieTableContainer").scrollTop($($('#ieContainer').children('tbody').find('tr')[[wordList.indexOf(targetWord)]]).position().top - 50)
    }
    $('#newStopWord').val('')
}

function changeData(num) {
    $('#linkToPostButton').unbind()
    $('#linkToPostButton').click(() => {
        window.open(url[num - 1])
    })
    if (([1, 2, 3]).indexOf(num) >= 0) {
        $.ajax({
            url: '/resource/dcardPosts/' + num + '.tsv',
            async: false,
            success: (data) => {
                tsvString = data
            }
        })
        $.ajax({
            url: '/resource/dcardPosts/' + num + '.json',
            async: false,
            success: (data) => {
                commentsInfo = data
            }
        })
        buildSentetree()
        return
    }
}

function showIdfEditor() {
    $(window).unbind('keydown')
    $(window).keydown(function(event) {
        if (event.keyCode == 13) {
            scrollIdfList()
        }
    })
    $('#ieContainer').empty().append(
            $('<thead>').append($('<tr>')
                .append($('<th>')
                    .attr('style', 'position: sticky; top: 0; background: white;')
                    .append('單詞'))
                .append($('<th>'))
                .append($('<th>').attr('class', 'w3-right-align')
                    .attr('style', 'position: sticky; top: 0; background: white;')
                    .append('單詞頻率')
                )
            )
        )
        .append($('<tbody>'))
    for (word of Object.entries(idfTable).sort((a, b) => { return (b[1] - a[1]) }).map((a) => { return a[0] }).slice(0, 1000)) {
        $('#ieContainer').find('tbody')
            .append($('<tr>')
                .attr('class', 'w3-display-container')
                .append($('<td>')
                    .attr('style', 'vertical-align: middle;')
                    .append(word))
                .append($('<td>')
                    .attr('class', 'w3-right-align')
                    .append($('<button>')
                        .attr('class', 'general-button')
                        .html('設為最小')
                        .click(function() {
                            $(this)
                                .parent()
                                .parent()
                                .find('input').val(0)
                        })
                    )
                    .append($('<button>')
                        .attr('class', 'general-button')
                        .html('設為最大')
                        .click(function() {
                            $(this)
                                .parent()
                                .parent()
                                .find('input').val(Object.values(idfTableOrig).reduce((a, b) => {
                                    return a > b ? a : b
                                }))
                        })
                    )
                    .append($('<button>')
                        .attr('class', 'general-button')
                        .html('重設')
                        .click(function() {
                            var _word = $($(this)
                                .parent()
                                .parent()
                                .find('td')[0]).html()
                            $(this)
                                .parent()
                                .parent()
                                .find('input').val(idfTableOrig[_word])
                        })
                    )
                )
                .append($('<td>')
                    .attr('class', 'w3-right-align')
                    .attr('style', 'vertical-align: middle;')
                    .append($('<input>')
                        .attr('type', 'number')
                        .val(idfTable[word])
                    )
                )
            )
    }
    $('#idfEditorLayer').removeClass('hidden')
}

function destroyCurrentGraph() {
    d3.selectAll('#vis').remove()
    d3.select('#graph').append('div').attr('id', 'vis')
}

function hidePopup() {
    $('#infoWindowLayer').toggleClass('hidden')
    $('#progressInfo').html('')
    $('#progBarInner').css('width', 0 + '%')
    closeEventListner()
}

function buildSentetree() {
    destroyCurrentGraph()
    console.log("Build.")
    var model;
    var tree;
    var data;
    console.log(tsvString)
    if (typeof tsvString === 'undefined') {
        d3.tsv(tsvPath, buildTree)
    } else {
        data = d3.tsvParse(tsvString)
        buildTree(_, data)
    }

    function buildTree(error, rawdata) {
        const data = rawdata.map(d => Object.assign({}, d, { count: +d.count }));
        model = new SentenTree.SentenTreeBuilder()
            .tokenize(SentenTree.tokenizer.tokenizeBySpace)
            .transformToken(token => (/score(d|s)?/.test(token) ? 'score' : token))
            .buildModel(data, {
                maxSupportRatio: 0.8,
                minSupportRatio: 0.001
            });
        tree = new SentenTree.SentenTreeVis('#vis', {
            fontSize: [15, 40],
            gapBetweenGraph: 10
        });
        console.log(tree)
        tree.data(model.getRenderedGraphs(2))
            .on('nodeClick', node => {
                seqList = node.data.seq.DBs.map(function(n) {
                    return n.rawText
                })
                let titleList = []
                for (s of seqList) {
                    titleTemp = commentsInfo.filter((v, i) => {
                        console.log(v)
                        return v['posseg']
                    })
                    if ((titleList.map(function(n) {
                            return n.title
                        })).indexOf(titleTemp.title) == -1) {
                        titleList.push(titleTemp)
                    }
                }
                console.log(titleList)
                info = wordTitleList[node.data.entity]
                $('#titleListKeyword').html(node.data.entity)
                $('#titleListKeywordInfo').html('')
                if (stopwords.indexOf(node.data.entity) < 0) {
                    $("#addToStopwords").html('設為停用詞').css('background-color', '#379').click(() => {
                        stopwords.push(node.data.entity)
                        destroyCurrentGraph()
                        buildSentetree()
                        hideTitles()
                    })
                } else {
                    $("#addToStopwords").html('從停用詞移除').css('background-color', '#933').click(() => {
                        stopwords.pop(node.data.entity)
                        destroyCurrentGraph()
                        buildSentetree()
                        hideTitles()
                    })
                }
                $('#setToKeyword').click(() => {
                    $('#keywordBox').val(node.data.entity)
                    sendRequest()
                    hideTitles()
                })
                $('#titleListLayer').removeClass('hidden')
                $('#titleListContainer').empty()
                for (i of titleList) {
                    $('#titleListContainer').append(
                        $('<li>').attr('class', 'w3-panel').append(
                            $('<a>').attr('href', i.url).attr('target', '_blank').append(
                                $('<h4>').html(i.title)
                            ).append(
                                $('<span>').attr('style', 'margin: 0px 10px').html(i.author)
                            ).append(
                                $('<span>').attr('style', 'margin: 0px 10px').html(i.date)
                            ).append(
                                $('<span>').attr('style', 'margin: 0px 10px').html('推文數：' + i.pushes)
                            )
                        )
                    )
                }
            })
            .on('nodeMouseenter', node => {
                console.log(node)
                titles = node.data.topEntries.map(function(x) {
                    console.log(x)
                    return commentsInfo.find((v, i) => {
                        return v['posseg'].indexOf(x.rawText) >= 0
                    })['content']
                })
                console.log(titles)
                infoStr = ''
                for (index in titles) {
                    pos = titles[index].search(node.data.entity)
                    infoStr += '... ' + titles[index].slice(Math.max(0, pos - 20), Math.min(titles[index].length - 1, pos + 20)) + ' ...<br>'
                }
                $(nodeTitleContent).html(infoStr)
                $('#nodeTitle').removeClass('hidden')
                tree.highlightNeighbors(node)
            })
            .on('nodeMouseleave', node => {
                $('#nodeTitle').addClass('hidden')
                tree.clearHighlightNeighbors()
            }).on('layoutStart', layout => {
                console.log(layout)
            }).on('linkMouseenter', link => {
                console.log(link)
            })
        new ResizeSensor(jQuery('#d3kitRoot'), function() {
            var scale, origin;
            scale = Math.min(2, ($('#graph').outerWidth()) / ($('#d3kitRoot').outerWidth() + 60))

            $('#vis').css({
                transform: "scale(" + scale + ")",
                'transform-origin': 'top left'
            });
        })
    }
}