/**
 * node-webkit 第三方C++扩展，js封装
 * User: wjchang
 * Version: 1.0
 */
define(function (require, exports) {
    var tts = window.require('./node_modules/tts/tts');
    var fs = window.require('fs');

    /**
     * 异步文本合成语音
     * @param text 合成文本
     * @param speecher 发音人
     * @param audiopath 合成音频保存路径
     * @returns {*}
     */
    function runAsyncTTS(text,speecher,audiopath) {
        var def = jQuery.Deferred();
        var args = {"SynthText": text, "VoiceSpeecher": speecher, "WordSpeed": "3", "UseCSSML": "0", "AudioPath": audiopath};

        tts.asyncTTS(JSON.stringify(args),function(err,result) {
            def.resolve(result);
        });

        return def.promise();
    }

    /**
     * 用于异步合成多组单词
     * @param words 单词数组
     * @param speecher 发音人
     * @param audioPath 音频文件
     * @returns {*}
     */
    function textToSpeech(metaJson, speecher, audioPath) {
        var def = $.Deferred();

        var result = {originalWords:"", resultJsonArr:[]};

        var ttsCallBack = function(index) {
            if(index < metaJson.words.length) {
                var audioFile = audioPath +"/" + metaJson.words[index].audio;

                runAsyncTTS(metaJson.words[index].word,speecher,audioFile).done(function(retJson){
                    result.resultJsonArr.push(retJson);
                    //delete wav audios
                    for(var i=0;i<metaJson.words.length;i++){
                        var wavPath = audioPath + "/" +  metaJson.words[i].audio.replace(".mp3",".wav");
                        fs.unlink(wavPath, function(err) {
                            if (err) console.error(err);
                        });
                    }
                    ttsCallBack(++index);
                });
            }

            if(index == metaJson.words.length) {
                def.resolve(result);
            }
        };

        ttsCallBack(0);

        return def.promise();
    }

    /**
     * 用于异步合成情景对话的音频
     * @param metaJson 单词数组
     * @param speecher 发音人
     * @param audioPath 音频文件
     * @returns {*}
     */
    function situationDlgToSpeech(metaJson, speecher, audioPath) {
        var def = $.Deferred();
        var result = {resultJsonArr:[]};
        var ttsCallBack = function(index) {
            if(index < metaJson.sens.length) {
                var audioFile = audioPath +"/" + metaJson.sens[index].audio;
                //console.log(audioFile);
                runAsyncTTS(metaJson.sens[index].text,speecher,audioFile).done(function(retJson){
                    result.resultJsonArr.push(retJson);
                    //delete wav audios
                    for(var i=0;i<metaJson.sens.length;i++){
                        var wavPath = audioPath + "/" + metaJson.sens[i].audio.replace(".mp3",".wav");
                        fs.unlink(wavPath, function(err) {
                            if (err) console.error(err);
                        });
                    }
                    ttsCallBack(++index);
                });
            }

            if(index == metaJson.sens.length) {
                def.resolve(result);
            }
        };
        ttsCallBack(0);
        return def.promise();
    }

    /**
     * 用于异步合成多组单词 批量版
     * @param words 单词数组
     * @param speecher 发音人
     * @param audioPath 音频文件
     * @returns {*}
     */
    function textToSpeechBat(metaJson, speecher, audioPath) {
        var def = $.Deferred();
        var result = {originalWords:"", resultJsonArr:[]};
        var jsons="";
        for(var index=0;index < metaJson.words.length;index++) {
            var audioFile = audioPath +"/" + metaJson.words[index].audio;
            var args = '{"SynthText": "'+metaJson.words[index]['word']+'", "VoiceSpeecher": "'+speecher+'", "WordSpeed": "3", "UseCSSML": "0", "AudioPath": "'+audioFile+'"}';
            jsons += args + "|";
        }
        jsons = jsons.substr(0,jsons.length-1);
        tts.asyncTTSBat(jsons,function(err,ret) {
            result['resultJsonArr'] = ret.split('|');
            //delete wav audios
            for(var i=0;i<metaJson.words.length;i++){
                var wavPath = audioPath + "/" +  metaJson.words[i].audio.replace(".mp3",".wav");
                fs.unlink(wavPath, function(err) {
                    if (err) console.error(err);
                });
            }
            def.resolve(result);
        });
        return def.promise();
    }

    function textToSpeechWithTryTimes(metaJson, speecher, audioPath,times) {
        var def = $.Deferred();
        var ttsRet = null;
        var ttsCallBack = function(index) {
            if(index < times) {
                textToSpeechBat(metaJson,speecher,audioPath).done(function (ret) {
                    console.log("textToSpeechWithTryTimes:"+JSON.stringify(ret));
                    ttsRet = ret;
                    var resultJsonArr = ret.resultJsonArr;
                    var audioFlag = true;
                    for(var i=0;i<resultJsonArr.length;i++) {
                        if(resultJsonArr[i] == "") {
                            audioFlag = false;
                            break;
                        }
                        var retObj = JSON.parse(resultJsonArr[i]);
                        console.log(retObj['audioFlag']);
                        if(retObj['audioFlag'] == 'false' || retObj['result']=="") {
                            audioFlag = false;
                            break;
                        }
                    }
                    console.log(audioFlag);
                    if(audioFlag == false) {
                        console.log("textToSpeechWithTryTimes Fail, try again!");
                        ttsCallBack(++index);
                    }else {
                        console.log("textToSpeechWithTryTimes succeed,return");
                        def.resolve(ret);
                    }
                });
            }

            if(index == times) {
                console.log("textToSpeechWithTryTimes timesover,return");
                def.resolve(ttsRet);
            }
        };

        ttsCallBack(0);
        return def.promise();
    }

    function situationDlgToSpeechBat(metaJson, speecher, audioPath) {
        var def = $.Deferred();
        var result = {originalWords:"", resultJsonArr:[]};
        var jsons="";
        for(var index=0;index < metaJson.sens.length;index++) {
            var audioFile = audioPath +"/" + metaJson.sens[index].audio;
            var text = metaJson.sens[index].text;
            text = text.replace(/[\.\?!，。？！]/gi,',');
            text = text.replace(/[^a-zA-Z'\s,\uff0c]/g, ' ');
            console.log(text);
            var args = '{"SynthText": "'+text+'", "VoiceSpeecher": "'+speecher+'", "WordSpeed": "3", "UseCSSML": "0", "AudioPath": "'+audioFile+'"}';
            jsons += args + "|";
        }
        jsons = jsons.substr(0,jsons.length-1);
        tts.asyncTTSBat(jsons,function(err,ret) {
            result['resultJsonArr'] = ret.split('|');
            //delete wav audios
            for(var i=0;i<metaJson.sens.length;i++){
                var wavPath = audioPath + "/" + metaJson.sens[i].audio.replace(".mp3",".wav");
                fs.unlink(wavPath, function(err) {
                    if (err) console.error(err);
                });
            }
            def.resolve(result);
        });
        return def.promise();
    }

    function situTTSWithTryTimes(metaJson, speecher, audioPath,times) {
        var def = $.Deferred();
        var ttsRet = null;
        var ttsCallBack = function(index) {
            if(index < times) {
                situationDlgToSpeechBat(metaJson,speecher,audioPath).done(function (ret) {
//                    console.log("situTTSWithTryTimes:");
//                    console.log(ret);
                    ttsRet = ret;
                    var resultJsonArr = ret.resultJsonArr;
                    var audioFlag = true;
//                    console.log(resultJsonArr.length);
                    for(var i=0;i<resultJsonArr.length;i++) {
//                        console.log(resultJsonArr[i]);
                        if(resultJsonArr[i] == "") {
                            audioFlag = false;
                            break;
                        }
                        var retObj = JSON.parse(resultJsonArr[i]);
//                        console.log(retObj);
//                        console.log(retObj['audioFlag']);
                        if(retObj['audioFlag'] == 'false' || retObj['result']=="") {
                            audioFlag = false;
                            break;
                        }
                    }
//                    console.log(audioFlag);
                    if(audioFlag == false) {
                        console.log("situTTSWithTryTimes Fail, try again!");
                        ttsCallBack(++index);
                    }else {
                        console.log("situTTSWithTryTimes succeed,return");
                        def.resolve(ret);
                    }
                });
            }

            if(index == times) {
                console.log("situTTSWithTryTimes timesover,return");
                def.resolve(ttsRet);
            }
        };

        ttsCallBack(0);
        return def.promise();
    }

    exports.textToSpeechWithTryTimes = textToSpeechWithTryTimes;
    exports.situTTSWithTryTimes =situTTSWithTryTimes;
});
