/// <reference path="../SpeechJS.js" />
/// <reference path="../../iFlyPlayer/iFlyPlayer.js" />

/**
 * 文件名: SmartBookPlayerAdapter.js
 * 描述: SmartBookPlayerAdapter SpeechJS适配器
 *
 * 功能说明：
 * 封装SmartBookPlayerAdapter播放器功能，提供给SpeechJS使用
 *
 * 版本: 1.0.0.0
 * 作者: yuwang@iflytek.com
 * 日期：2012/07/03
 *
 * 变更记录：
 *
 */

(function (win) {

    var _player;

    /**
     * 调用客户端命令
     * @param {string} cmdRegion 模块名称
     * @param {string} cmdName 命令名
     * @param {string} cmdArgs 多个参数，参数间使用|分隔
     * @param {string=} cmdType 命令类别
     * @returns {string}
     */
    win.callClient=function(cmdRegion, cmdName, cmdArgs, cmdType, callback) {
        var funcName = cmdRegion + '.' + cmdName;
        if (callback) {
            var wrapper=function(name,args){
                //删除注册的函数
                //cef.message.removeMessageCallback(funcName, this);
                callback(args[0]);
                //console.log('name:',name,'args:',args);
            };
            cef.message.sendMessage(funcName, [cmdArgs, cmdType.toString()]);
            cef.message.setMessageCallback(funcName, wrapper);
        } else {
            //无回调
            cef.message.sendMessage(funcName, [cmdArgs, cmdType.toString()]);
        }
    }

    /**
     *
     * @param option
     * @returns {*}
     * @constructor
     */
    function SmartBookPlayerAdapter(option) {

        if(_player) {
            return _player;
        }

        var _this = _player = this;
        option = option || {};
        option.events = option.events || {};
        var _audioUrl;
        var _isPause;
        var _sndLen;

        window.addEventListener('message', function (e) {

            var data;
            if(typeof e.data === "string"){
                data = eval('(' + e.data + ')');
            }else{
                data = e.data;
            }

            if (!data || !data.evt)   {
                return;
            }

            var playerEventType = data.evt;
//            console.log("%c【回调响应】，事件类型：%s", "color:blue", data.evt);
            if (playerEventType == 'play_start') {
                option.events.onPlayBegin && option.events.onPlayBegin.call(_this,{duration:_sndLen});
            }
            else if (playerEventType == 'play_resume') {
                option.events.onPlayBegin && option.events.onPlayBegin.call(_this,{duration:_sndLen});
            }
            else if (playerEventType == 'play_pause') {
                option.events.onPause && option.events.onPause.call(_this);
            }
            else if (playerEventType == 'play_end') {
                option.events.onStop && option.events.onStop.call(_this);
            }
            else if(playerEventType == 'playing') {
                if(option.events.onPlaying) {
                    var info = e.data.split(' ');
                    var playingParam = {position: parseFloat(info[0]), energy: parseInt(info[1])};
                    option.events.onPlaying.call(_this, playingParam);
                }
            }
        }, false);

        //------------------------------------------ events  --------------------------------------------

//        this.onReady = function () { this.__proxy__.addEventListener("onReady", arguments[0]); };
//        this.onError = function () { this.__proxy__.addEventListener("onError", arguments[0]); };
//        this.onPlayBegin = function () { this.__proxy__.addEventListener("onPlayBegin", arguments[0]); };
//        this.onPlaying = function () { this.__proxy__.addEventListener("onPlaying", arguments[0]); };
//        this.onBuffering = function () { this.__proxy__.addEventListener("onBuffering", arguments[0]); };
//        this.onPause = function () { this.__proxy__.addEventListener("onPause", arguments[0]); }; ;
//        this.onStop = function () { this.__proxy__.addEventListener("onStop", arguments[0]); }; ;

        //------------------------------------------ public method ---------------------------------------
        this.__proxy__.loadAudio = function (url) {
            url = decodeURI(url);
            _audioUrl = url;
            _isPause = false;
//          _sndLen = callClient('syscmd', 'sndaudiolen', _audioUrl);
        };

        this.__proxy__.play = function () {
            if(_isPause) {
                callClient('syscmd', 'sndresume', '', 0);
            } else{
                callClient('syscmd', 'sndplay', _audioUrl, 2);
            }
            //callClient('syscmd', 'sndresume', '', 1);
        };

        this.__proxy__.playRange = function (beginPos, endPos) {
            callClient('syscmd', 'sndplayRange', [_audioUrl, beginPos, endPos].join('|'), 2);
        };

        this.__proxy__.pause = function () {
            callClient('syscmd', 'sndpause', '', 0);
            _isPause = true;
        };

        this.__proxy__.stop = function () {
            callClient('syscmd', 'sndstop', '', 0);
            _isPause = false;
        };

        this.__proxy__.getVolume = function () {
            //TODO: callCient()
        };

        this.__proxy__.setVolume = function (volume) {
            //TODO: callCient()
        };

        this.__proxy__.setMute = function (isMute) {
            //TODO: callCient()
        };

        this.__class__.check.call(this);

        // 模拟播放器准备完成事件
        setTimeout(function(){
            option.events.onReady && option.events.onReady.call(_this);
        },0);
    };

    SmartBookPlayerAdapter.prototype = new SpeechJS.PlayerAdapterBase();
    SmartBookPlayerAdapter.prototype.constructor = SmartBookPlayerAdapter;

    win.SmartBookPlayerAdapter = SmartBookPlayerAdapter;
})(window);