/**
 * Created with JetBrains WebStorm.
 * User: qingwu
 * Date: 13-7-20
 * Time: 下午6:41
 * To change this template use File | Settings | File Templates.
 */
String.prototype.startsWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}

var app_global_player = {};
app_global_player.player = $("#player")[0];
app_global_player.onMessageReceived = function (msg) {
    if (!msg || !msg.evt)
        return;

    console.log('---------onMessageReceived---------' + JSON.stringify(msg));
    //if (msg.evt == 'play_start') {
    //    app_global_player.player.src = msg.data.filePath;
    //    app_global_player.player.play();
    //}
}


var commAdapter = commAdapter || {};

/**
 * 接收java端发送的消息
 * @param msg
 */
commAdapter.dispatchClientMsg = function (msg) {
    if (!msg) return;
    if (msg.evt.startsWith('play_') && app_global_player) {
        app_global_player.onMessageReceived(msg);
    }
    dispatchClientMsg(msg);
}

function dispatchClientMsg(msg) {
    console.log(msg);
    document.getElementById(iframeID).contentWindow.postMessage(msg, "*");
}

/**
 * js调Android方法集合
 */
commAdapter.callAndroid = {
    /**
     * Android接口
     */
    commInterface: window.commInterface,
    closeBookShopInterface: window.closeBookShopInterface,
    closeBookShop: function (value) {
        return this.closeBookShopInterface.setBookShopHide(value);
    },
    bookIsExists: function (bookcode) {
        return this.closeBookShopInterface.bookIsExist(bookcode);
    },
    callShow: function () {
        return this.commInterface.showCard();
    },

    openDownLoadFile: function (title) {
        this.commInterface.openDownloadFile(title);
    },

    /**
     * 获取当前用户名
     * @returns {*}
     */
    getUserId: function () {
        return this.commInterface.getUserId();
    },


    finishSmartBook: function () {
        this.commInterface.finishSmartBook();
    },

    /**
     * 设置当前课本ID
     * @param bookCode
     */
    setBookCode: function (bookCode) {
        this.commInterface.setBookCode(bookCode);
    },
    showBlackBoard: function (evtName) {
        this.commInterface.showBlackBoard(evtName);
    },
    /**
     * 设置webview默认缩放比例，阻止软键盘弹出时放大页面
     */
    setDefaultScale: function () {
        this.commInterface.setDefaultScale();
    },
    setWebViewZoom: function (flag) {
        this.commInterface.setWebViewZoom(flag);
    },
    //adxing 2013 09 24
    /**
     *  事件驱动
     * @param evtName
     * @param data
     * @returns {*}
     */
    onEventProcess: function (evtName, data, arg0, arg1) {

        return this.commInterface.onEventProcess(evtName, data, arg0, arg1);
    },
    showShellCard: function (evtName, data, arg0, arg1) {
        return this.commInterface.showShellCard(evtName, data, arg0, arg1);
    },

    /**
     * 设置当前url是否index_android.html页面
     * @param url
     */
    setIsIndex: function (value) {
        this.commInterface.setIsIndex(value);
    },

    setTurnPageIndex: function (value) {
        this.commInterface.setTurnPageIndex(value);
    },

    setIsIndexLoaded: function (value) {
        this.commInterface.setIsIndexLoaded(value);
    },

    getTurnPageIndex: function () {
        return this.commInterface.getTurnPageIndex();
    },

    /**
     * 获取当前课本ID
     * @param bookCode
     */
    getBookCode: function () {
        return this.commInterface.getBookCode();
    },

    /**
     * 获取文件类容
     * @param xmlPath
     * @returns {*}
     */
    readFile: function (filePath) {
        return this.commInterface.readFile(filePath);
    },

    /**
     * 从Asset下获取文件内容
     */
    readFileFormAsset: function (filePath) {
        return this.commInterface.readFileFormAsset(filePath);
    },

    /**
     * 写文件
     * @param xmlPath
     * @returns {*}
     */
    writeFile: function (filePath, content) {
        return this.commInterface.writeFile(xmlPath, content);
    },

    /**
     * 获取图片的base64编码
     * @param bookCode 资源id
     * @param imgName 图片名称
     * @returns {{readXML: Function}|*}
     */
    getImgBase64: function (imgPath) {
        return this.commInterface.getImgBase64(imgPath);
    },
    /**
     * 播放ppt、word等文件
     * @param packagePath
     * @param filePath
     * @returns {*}
     */
    showProc3dFile: function (packagePath, filePath) {
        this.commInterface.showProc3dFile(packagePath, filePath);
    },

    /**
     * 关闭播放ppt等文件的activity
     */

    closeProc3dFile: function () {
        this.commInterface.closeProc3dFile();
    },

    /**
     * 获取文件类容，从包中
     * @param xmlPath
     * @returns {*}
     */
    readFileFromPck: function (packagePath, filePath) {
        return this.commInterface.readFileFromPck(packagePath, filePath);
    },

    /**
     * 获取文件类容，从包中
     * @param xmlPath
     * @returns {*}
     */
    readXMLFromPck: function (packagePath, filePath) {
        return this.commInterface.readUTF8FromPck(packagePath, filePath);
    },
    /**
     * 获取图片的base64编码
     * @param bookCode 资源id
     * @param imgName 图片名称
     * @returns {{getImgBase64FromPck: Function}|*}
     */
    getImgBase64FromPck: function (packagePath, filePath) {
        return this.commInterface.getImgBase64FromPck(packagePath, filePath);
    },

    /**
     * 获取临时目录
     * @param url
     * @returns {*}
     */
    getELPTempPath: function () {
        return this.commInterface.getELPTempPath();
    },

    writeTempFileFromPck: function (packagePath, filePath) {
        return  this.commInterface.writeTempFileFromPck(packagePath, filePath);
    },

    modifyVoice: function () {
        this.commInterface.modifyVoice();
    },

    setWidgetStopFlag: function (flag) {
        this.commInterface.setWidgetStopFlag(flag);
    },

    getCheckSum: function (bookId) {
        return  this.commInterface.getCheckSum(bookId);
    },

    /**
     * 异步调用测试代码
     * @param callBack
     */
    httpGetRequest: function (url, evtName, callBack) {
        this.commInterface.httpGetRequest(url, evtName);
        if (typeof callBack === 'function' && eventDispatcher) {
            eventDispatcher.addEventListener(evtName, callBack);
        }
    },

    /**
     * 异步调用http Post Request
     * @param callBack
     */
    httpPostRequest: function (url, content, evtName, callBack) {
        this.commInterface.httpPostRequest(url, content, evtName);
        if (typeof callBack === 'function' && eventDispatcher) {
            eventDispatcher.addEventListener(evtName, callBack);
        }
    },

    /**
     * 创建Cache
     * @param cacheType cache type: 1, 2, 3
     * @param size 限制值
     */
    createCache: function (cacheName, cacheType, size) {
        return this.commInterface.createCache(cacheName, cacheType, size);
    },

    /**
     * query Cache Item
     */
    queryCacheItem: function (cacheName, keyname) {
        return this.commInterface.queryCacheItem(cacheName, keyname);
    },

    /**
     * set Cache Item
     */
    setCacheItem: function (cacheName, keyname, content) {
        this.commInterface.setCacheItem(cacheName, keyname, content);
    },

    /**
     * 清除 Cache Item
     */
    clearCacheItem: function (cacheName, keyname) {
        this.commInterface.clearCacheItem(cacheName, keyname);
    },
    startPing: function () {
        return this.commInterface.startPing();
    },
    /**
     * 处理自定义事件
     */
    processEvent: function (evtName, data, arg1, arg2) {
        return this.commInterface.processEvent(evtName, data, arg1, arg2);
    },

    /**
     * query SQLite
     */
    rawQuerySQLite: function (sql, content) {
        return this.commInterface.rawQuerySQLite(sql, content);
    },

    querySQLite: function (table, content) {
        return this.commInterface.querySQLite(table, content);
    },

    /**
     * insert SQLite
     */
    insertSQLite: function (table, content) {
        return this.commInterface.insertSQLite(table, content);
    },

    /**
     * update SQLite
     */
    updateSQLite: function (table, values, whereClause) {
        return this.commInterface.updateSQLite(table, values, whereClause);
    },

    /**
     * delete SQLite
     */
    deleteSQLite: function (table, whereClause) {
        return this.commInterface.deleteSQLite(table, whereClause);
    },

    execSQL: function (sql) {
        return this.commInterface.execSQL(sql);
    },

    /**
     * 调用拍照
     * @param evtName 回调函数名
     * @param callback 回调函数
     * @returns {*}
     */
    playCamera: function (evtName, callback) {
        if (typeof callback === 'function' && eventDispatcher) {
            eventDispatcher.addEventListener(evtName, callback);
        }
        this.commInterface.playCamera(evtName);
    },

    /**
     * 播放音频 从资源包中
     */
    playAudioFromPck: function (packagePath, filePath) {
        //console.log('------------playAudioFromPck::-----------' + filePath);
        this.commInterface.playAudioFromPck(packagePath, filePath);
    },
    /**
     * 播放音频 从资源包中
     */
    playFormUri: function (uri) {
        //console.log('playFormUri:' + uri);
        this.commInterface.playFormUri(uri);
    },

    /**
     * 播放视频 从资源包中
     */
    playVideoFromPck: function (packagePath, filePath) {
        return this.commInterface.playVideoFromPck(packagePath, filePath);
    },
    /**
     * 停止正在播放的音频
     */
    stopPlayAudio: function () {
        this.commInterface.stopPlayAudio();
    },

    /**
     * 暂停正在播放的音频
     */
    pausePlayAudio: function () {
        this.commInterface.pausePlayAudio();
    },

    /**
     * 继续播放音频
     */
    continuePlayAudio: function () {
        this.commInterface.continuePlayAudio();
    },

    /**
     * 播放视频 从资源路径
     */
    playVideoFromPath: function (filePath) {
        return this.commInterface.playVideoFromPath(filePath);
    },

    /**
     * 判断userbook目录下的文件是否存在
     * @param packagePath
     * @param filePath
     * @returns {*}
     */
    isUserFileExist: function (packagePath, filePath) {
        return this.commInterface.isUserFileExist(packagePath, filePath);
    },

    /**
     * 获取图片的base64编码
     * @param bookCode 资源id
     * @param imgName 图片名称
     * @returns {{getImgBase64FromPck: Function}|*}
     */
    getImgBase64FromUser: function (packagePath, filePath) {
        return this.commInterface.getImgBase64FromUser(packagePath, filePath);
    },

    /**
     * 获取图片的base64编码
     * @param bookCode 资源id
     * @param imgName 图片名称
     * @returns {{getImgBase64FromPck: Function}|*}
     */
    getImgUrlFromUser: function (packagePath, filePath) {
        return this.commInterface.getImgUrlFromUser(packagePath, filePath);
    },

    /**
     * 保存文件至userbook下
     * @param packagePath
     * @param filePath
     * @param content
     */
    writeFileFromUser: function (packagePath, filePath, content) {
        this.commInterface.writeFileFromUser(packagePath, filePath, content);
    },

    /**
     * 删除文件
     * @param packagePath
     * @param filePath
     */
    deleteFileFromUser: function (packagePath, filePath) {
        this.commInterface.deleteFileFromUser(packagePath, filePath);
    },

    /**
     * 读取userbook下的文件
     * @param packagePath
     * @param filePath
     */
    readFileFromUser: function (packagePath, filePath) {
        return this.commInterface.readFileFromUser(packagePath, filePath);
    },

    downloadBook: function (args) {
        return  this.commInterface.downloadBook(args);
    },
    canceldownloadBook: function (args) {

        return   this.commInterface.canceldownloadBook(args);
    },
    cancelalldownloadBook: function () {
        return this.commInterface.cancelAlldownloadBook();
    },
    closedActorCard: function () {
        return this.commInterface.closedActorCard();
    },

    showNoteView: function (content) {
        return this.commInterface.showNoteView(content);
    },
    closeNoteView: function () {
        return this.commInterface.closeNoteView();
    },
    /**
     * 获取webview宽高
     * @returns {*}
     */
    getWebSize: function () {
        return this.commInterface.getWebSize();
    },
    /**
     * 打开课本页面
     * @returns {*}
     */
    openSmartBook: function () {
        return this.commInterface.openSmartBook();
    }
}

/**
 * 卡片播放器对象
 * @type {{play: Function, playStop: Function}}
 */
commAdapter.player = {
    playerInterface: window.playerInterface,

    /**
     * 音频预加载
     * @param packagePath
     * @param filePath
     */
    loadAudio: function (filePath) {
        this.playerInterface.loadAudio(filePath);
    },
    /**
     * 播放音频
     * @param packagePath 资源包id
     * @param filePath 本地文件路径
     */
    play: function (packagePath, filePath) {
        this.playerInterface.play(packagePath, filePath);
    },
    /**
     *  播放音频
     * @param beginPos
     * @param endPos
     */
    playRange: function (beginPos, endPos) {
        this.playerInterface.playRange(beginPos, endPos);
    },
    /**
     * 播放音频
     * @param filePath 本地文件路径
     */
    playFromUri: function (filePath) {
        this.playerInterface.playFromUri(filePath);
    },

    /**
     * 停止播放
     */
    playStop: function () {
        this.playerInterface.playStop();
    }

}

/**
 * 卡片录音器对象
 * @type {{recorderInterface: *, record: Function, stop: Function, loadAudio: Function, play: Function, playRange: Function, pause: Function, stopPlay: Function}}
 */
commAdapter.recorder = {
    recorderInterface: window.recorderInterface,

    /**
     * 录音
     * @param {JSON} recordOption {evalType: "read_word", evalText: "[word]?sheep?horse?hen?cow?goat?lamb", evalParams: "vadEnable=true, vadSpeechTail=2500", sndId: "word-card-1375859197931"}
     */
    record: function (recordOption) {
        console.log(this.recorderInterface);
        this.recorderInterface.record(recordOption);
    },

    /**
     * 停止评测录音
     * @param {boolean} isForce  true:强制停止评测(不会有后续事件的调用) false:正常停止录音
     */
    stop: function (isForce) {
        this.recorderInterface.stop(isForce);
    },
    /**
     * 播放用户录音
     * @param audioId
     * @param {boolean} autoPlay true 自动播放 false 只加载不播放
     */
    loadAudio: function (audioId, autoPlay) {
        this.recorderInterface.loadAudio(audioId, autoPlay);
    },

    /**
     * 播放用户录音，该方法调用前应先调用 loadAudio
     */
    play: function () {
        this.recorderInterface.play();
    },

    /**
     * 播放区域音频
     * @param begPos 开始位置
     * @param endPos 结束位置j
     */
    playRange: function (begPos, endPos) {
        //Java 判断如果endpos<0则停止播发
        if (begPos === 0 && endPos === 0) {
            endPos = -1;
        }
        this.recorderInterface.playRange(begPos, endPos);
    },

    /**
     * 暂不实现
     */
    pause: function () {
        this.recorderInterface.pause();
    },

    /**
     * 停止播放用户录音
     */
    stopPlay: function () {
        this.recorderInterface.stopPlay();
    }

}
