/**
 * @Author  HonorLee (dev@honorlee.me)
 * @Version 1.0 (2019-04-21)
 * @License MIT
 */
var bg,currentWord,wordObj;
var wordInfoApi = 'https://api.shanbay.com/bdc/search/';
var wordSentenceApi = 'https://api.shanbay.com/bdc/example/';
var audio = new Audio();
$(function(){
    $('.word a.audio').click(function(){
        audio.src = wordObj.info.audio;
        audio.play();
    });
    $('.info a.close').click(function(){
        chrome.app.window.current().close();
    });
});

chrome.runtime.onMessage.addListener(function(msg){
    if(msg=="updateInfo") build();
})

function build(){
    $('.loading').addClass('on');
    chrome.runtime.getBackgroundPage(function(background){
        bg          = background;
        currentWord = bg.currentWord;
        wordObj     = bg.wordDataObj[currentWord];
        initWordInfo();
    });
}

function initWordInfo(){
    if(wordObj['info']){
        initWordSentence();
    }else{
        $.ajax({
            method:'GET',
            url:wordInfoApi,
            data:{word:currentWord},
            dataType:'json',
            success:function(res){
                if(res.msg=="SUCCESS"){
                    wordObj.info = {
                        id:res.data.id,
                        audio:res.data.audio,
                        pron:res.data.pronunciation,
                        definition:res.data.definition.split('\n')
                    }
                    chrome.storage.local.set({wordsObj:bg.wordDataObj});
                    initWordSentence();
                }else{
                    console.log(res.msg);
                }
            },
            error:function(e){
                console.log('ERROR',e);
                // alert('接口调用失败')
            }
        });
    }
}

function initWordSentence(){
    if(wordObj['example']){
        fillContent();
    }else{
        $.ajax({
            method:'GET',
            url:wordSentenceApi,
            data:{vocabulary_id:wordObj.info.id,type:'sys'},
            dataType:'json',
            success:function(res){
                if(res.msg=="SUCCESS"){
                    var samples = res.data;
                    var exampleArr = [];
                    if(samples.length>0){
                        // console.log(samples.length)
                        for(var i = 0;i<samples.length;i++){
                            var sentence = samples[i];
                            exampleArr.push({
                                sentence:sentence.annotation,
                                trans:sentence.translation
                            });
                            if(i==4) break;
                        }
                    }
                    wordObj.example = exampleArr;
                    chrome.storage.local.set({wordsObj:bg.wordDataObj});
                }else{
                    console.log(res.msg);
                }
                fillContent();
            },
            error:function(e){
                console.log('ERROR',e);
                // alert('接口调用失败')
            }
        });
    }
}

function fillContent(){
    var newWord = currentWord.split('');
    newWord[0] = (newWord[0]).toUpperCase();
    newWord = newWord.join('');
    $('.word .w').text(newWord);
    $('.word .pron span').text(wordObj.info.pron);
    $('.def').empty();
    $('.example').empty();
    wordObj.info.definition.forEach(function(def){
        $('.def').append('<p>'+def+'</p>');
    });
    wordObj.example.forEach(function(ex){
        $('.example').append('<div class="ex"><p>'+ex.sentence+'</p><p>'+ex.trans+'</p></div>')
    })
    chrome.app.window.current().resizeTo(300,$('.info').height()+40);
    $('.loading').removeClass('on');
}