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

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

    chrome.notifications.onButtonClicked.addListener(function(e,index){
        if(e=='deleteword'){
            if(index==0) bg.deleteWord(delWord);
            delWord = null;
        }
        if(e=='clearData' && index==0) bg.clearDatas();
    })

    $('.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>');

    });
    $('.tabContent .list').on('click','li a.del',function(){
        delWord = $(this).parents('li').data('word');
        chrome.notifications.create('deleteword',{iconUrl:'../asset/img/logo@x128.png',message:'确定从词库中删除['+delWord+']单词么?',type:'basic',title:'移除单词!',buttons:[{title:'Yes'},{title:'No'}]});
        // if(confirm('确定从词库中删除['+word+']单词么?')){
        //     bg.deleteWord(word);
        // }
    });
    $('.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(){
        if($('#my_file')[0].files.length==0) return;
        $('.loading').addClass('on').find('p').text('词库导入中,请稍后...');
        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");
            bg.importWord(tmpArr);
        }
    });
    $('.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');
        })
    });
    $('.settings button#importWord').click(function(){
        chrome.app.window.create('windows/import.html', {
            id:'import',
            resizable:false,
            alwaysOnTop:true,
            innerBounds:{width:300,height:400},
            // hidden:true,
            frame:{type:'none'}
        });
    });

    $('.importForm .ok').click(function(){
        var list = $('.importForm textarea').val().split('\n');
        bg.importWord(list);
        chrome.app.window.current().close();
    });
    $('.importForm .cancel').click(function(){
        chrome.app.window.current().close();
    });
    $('button#clearData').click(function(){
        chrome.notifications.create('clearData',{iconUrl:'../asset/img/logo@x128.png',message:'确定清除全部数据么?',type:'basic',title:'清除数据!',buttons:[{title:'Yes'},{title:'No'}]});
    });
});

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