/**
 * @Author  HonorLee (dev@honorlee.me)
 * @Version 1.0 (2019-04-21)
 * @License MIT
 */
var bg;
$(function(){
    $('.loading').addClass('on').find('p').text('词库读取中,请稍后...');
    chrome.runtime.getBackgroundPage(function(background){
        bg = background;
        buildNormalList();
        buildStarList();
        $('.showTimeSets input').val(bg.setting.timerMin);
    });

    chrome.runtime.onMessage.addListener(function(msg){
        if(msg=="updateStarList") buildStarList();
    })

    $('.tabContent .list').on('click','li a.info',function(){
        var word = $(this).parents('li').data('word');
        bg.showWordInfo(word);
    });
    $('.tabContent .list').on('click','li a.star',function(){
        var word = $(this).parents('li').data('word');
        var nowType = $(this).data('star');
        if(nowType=='undefined') nowType = 0;
        var toType = Math.abs(nowType-1);
        bg.starWord(toType,word);
        $(this).data('star',toType);
        $(this).html('<i class="fa fa-star'+(toType==1?'':'-o')+'"></i>');

    });
    $('.title a.minimize').click(function(){
        chrome.app.window.current().minimize();
    });
    $('.title a.close').click(function(){
        chrome.app.window.current().close();
    });
    $('.tabContent .search').on('keyup',function(){
        var word = $(this).val();
        $(this).parent().find('.list li').hide().filter(":contains('"+word+"')").show();
    });
    $('.tabs a').click(function(){
        $(this).addClass('on').siblings().removeClass('on');
        $('.tabContent').removeClass('on').eq($(this).index()).addClass('on');
    });

    $("#clickme").click(function (source) {
        $("#my_file").trigger('click');
    })
    $("#my_file").on('change',function(){
        $('.loading').addClass('on').find('p').text('词库导入中,请稍后...');
        var wordCount = 0;
        var file = $('#my_file')[0].files[0];
        var reader = new FileReader();
        reader.readAsText(file, "utf-8");
        reader.onload = function (e) {
            var tmpArr = e.target.result.split("\n");
            var word;
            if(tmpArr.length>0){
                for(var i = 0;i<tmpArr.length;i++){
                    word = (tmpArr[i]).toLowerCase();
                    if(!bg.wordDataObj[word]){
                        wordCount++;
                        bg.wordDataObj[word] = {testCount:0}
                        bg.wordDataArr.push(word);
                    }
                    // wordsObj[word] = {testCount:0}
                };
                if(wordCount>0) bg.wordDataArr.sort();
            }
            chrome.storage.local.set({wordsArr:bg.wordDataArr,wordsObj:bg.wordDataObj},function(e){
                chrome.notifications.create('importNotifi'+(new Date().getTime()),{iconUrl:'../asset/img/logo@x128.png',message:'词库导入成功\n本次共导入['+wordCount+']个新单词',type:'basic',title:'导入完成!'});
                $('.loading').removeClass('on');
                // console.log('导入完成',e);
                buildNormalList();
            })
        }
    });
    $('.settings a.save').click(function(){
        bg.setting = {
            timerMin:$('input[name=showTime]').val()
        }
        chrome.storage.local.set({setting:bg.setting},function(e){
            bg.setTimer();
            chrome.notifications.create('importNotifi'+(new Date().getTime()),{iconUrl:'../asset/img/logo@x128.png',message:'设置已保存',type:'basic',title:'设置已保存!'});
            $('.loading').removeClass('on');
        })
    });
});

function buildNormalList(listIndex){
    $('.total .list ul').empty();
    $('.loading').addClass('on').find('p').text('词库读取中,请稍后...');
    var dom = ''
    if(bg.wordDataArr.length) bg.wordDataArr.forEach( function(word) {
        var starType = bg.wordDataObj[word]['isStar'];
        if(starType==undefined) starType=0;
        dom += '<li name="'+word+'" data-word="'+word+'">'+word+'<div class="btn"><a class="info" title="查看详情"><i class="fa fa-comment-o"></i></a><a class="star" data-star="'+starType+'" title="加入收藏"><i class="fa fa-star'+(starType==1?'':'-o')+'"></i></a><a class="del" title="移出词库"><i class="fa fa-trash-o"></i></a></div></li>';
    });
    $('.total .list ul').append(dom);
    $('.tabs a:eq(0) span').text('('+bg.wordDataArr.length+')');
    $('.loading').removeClass('on');
}

function buildStarList(listIndex){
    $('.starList .list ul').empty();
    $('.loading').addClass('on').find('p').text('收藏词库读取中,请稍后...');
    var dom = ''
    if(bg.wordStarArr.length) bg.wordStarArr.forEach( function(word) {
        var starType = bg.wordDataObj[word]['isStar'];
        if(starType==undefined) starType=0;
        dom += '<li data-word="'+word+'">'+word+'<div class="btn"><a class="info" title="查看详情"><i class="fa fa-comment-o"></i></a><a class="star" data-star="'+starType+'" title="加入收藏"><i class="fa fa-star'+(starType==1?'':'-o')+'"></i></a><a class="del" title="移出词库"><i class="fa fa-trash-o"></i></a></div></li>'
    });
    $('.starList .list ul').append(dom);
    $('.tabs a:eq(1) span').text('('+bg.wordStarArr.length+')');
    $('.loading').removeClass('on');
    buildNormalList();
}