/*
 * SpeechJS 初始化模块
 * @module speechui/common/resource
 * @date 2013/06/17
 */

define(function (require, exports) {

    var speechCMD = require('../speech/speechCMD');
    var mask      = require('./mask');
    var $         = require('jquery');
                    require('');

    var _speecher = {isReady : true};
    var _recordEvents;
    var _playEvents;
    var _maskOption;

    speechCMD.init(gUseLocalPlayer, gUseAndriodAdapter, function (useLocalPlayer, useAndriodAdapter) {

        if (window.JWPlayerSettings) {
            var jwpalyer = require.resolve('../../../speechui/code/speech/iFlyPlayer/jwplayer/player.swf#');
            window.JWPlayerSettings.PlayerSWF = jwpalyer;
        }

        if(window.SpeechRecorderSettings){
            var speechRecorderRoot = require.resolve('../../../speechui/code/speech/SpeechRecorder/');
            window.SpeechRecorderSettings.Root = speechRecorderRoot;
        }

        var playerAdapter = (!useLocalPlayer) ? SpeechJS.Adapters.JWPlayer:
                             useAndriodAdapter ? SpeechJS.Adapters.AndroidPlayer : SpeechJS.Adapters.SmartBookPlayer;

        var recordAdapter = useAndriodAdapter ? SpeechJS.Adapters.AndroidRecorder : SpeechJS.Adapters.SpeechRecorder;

        var speecher = SpeechJS.load({
            recorderOption: {
                adapter : recordAdapter,
                id      : "recorder",
                width   : "1px",
                height  : '1px',
                events  : {
                    onReady : function () {
                        speecher.Recorder.isReady = true;
                        LogUtil.info("Recorder is ready...");
                        _recordEvents.onReady && _recordEvents.onReady.call(this);
                    },
                    onError : function (e) {
                        _recordEvents.onError && _recordEvents.onError.call(this, e);
                        console.log("%c【speechui error】错误的类型：%O","color:blue", e);
//                        LogUtil.error("onError:" + $.toJSON(e));
                    },
                    onEvalResult : function (e) {
                        _recordEvents.onEvalResult && _recordEvents.onEvalResult.call(this, e);
                    },
                    onRecording : function (e) {
                        _recordEvents.onRecording && _recordEvents.onRecording.call(this, e);
                       // LogUtil.debug("onRecording:" + $.toJSON(e));
                    },
                    onMicrophoneState : setMicrophoneState,
                    onRecordBegin : function (e) {
                        _recordEvents.onRecordBegin && _recordEvents.onRecordBegin.call(this, e);
//                        LogUtil.info("onRecordBegin:" + $.toJSON(e));
                    },
                    onTrackInfo : function (e) {
                        _recordEvents.onTrackInfo && _recordEvents.onTrackInfo.call(this, e);
//                        LogUtil.info("onTrackInfo:" + $.toJSON(e));
                    },
                    onPlayBegin : function (e) {
                        _recordEvents.onPlayBegin && _recordEvents.onPlayBegin.call(this, e);
//                        LogUtil.info("player begin:" + $.toJSON(e));
                    },
                    onPlayStop : function (e) {
                        _recordEvents.onPlayStop && _recordEvents.onPlayStop.call(this, e);
//                        LogUtil.info("player stop:" + $.toJSON(e));
                    },
                    onPlaying : function (e) {
                        _recordEvents.onPlaying && _recordEvents.onPlaying.call(this, e);
//                        LogUtil.info("player playing:" + $.toJSON(e));
                    },
                    onAudioLoaded : function (e) {
                        _recordEvents.onAudioLoaded && _recordEvents.onAudioLoaded.call(this, e);
//                        LogUtil.debug("onAudioLoaded:" + $.toJSON(e));
                    },
                    onAudioCheckResult : function (e) {
                        _recordEvents.onAudioCheckResult && _recordEvents.onAudioCheckResult.call(this, e);
//                        LogUtil.debug("recorder onAudioCheckResult:" + e);
                    }
                }
            },
            playerOption: {
                adapter : playerAdapter,
                id      : "player",
                width   : "1px",
                height  : '1px',
                events  : {
                    onReady : function (e) {
                        speecher.Player.isReady = true;
//                        LogUtil.info("Player is ready...");
                        _playEvents.onReady && _playEvents.onReady.call(this,e);
                    },
                    onStop : function (e) {
                        _playEvents.onStop && _playEvents.onStop.call(this,e);
//                        LogUtil.info("Player onStop...");
                    },
                    onMeta : function (e) {
                        _playEvents.onMeta && _playEvents.onMeta.call(this,e);
//                        LogUtil.info("Player onMeta:" + $.toJSON(e));
                    },
                    onError : function (e) {
                        _playEvents.onError && _playEvents.onError.call(this,e);
                        console.error("Player onError:" + $.toJSON(e));
                    },
                    onPause : function (e) {
                        _playEvents.onPause && _playEvents.onPause.call(this,e);
//                        LogUtil.info("Player onPause...");
                    },
                    onPlaying : function (e) {
                        _playEvents.onPlaying && _playEvents.onPlaying.call(this,e);
                    },
                    onPlayBegin : function (e) {
                        _playEvents.onPlayBegin && _playEvents.onPlayBegin.call(this,e)
//                        LogUtil.info("Player onPlayBegin:" + $.toJSON(e));
                    }
                }
            }
        });

        // 扩展speecher对象
        console.log("%c【speechui _speecher】扩展对象完成",'color:blue;');
        parent.gSpeechCardLoadReady = true;
        $("body").css(gTransform);
        $.extend(_speecher, speecher);

        var playerInfo = speecher.Recorder.getFlashPlayerState();
//        LogUtil.info('Speech::Flash player version:' + $.toJSON(playerInfo));
        if(playerInfo.state != FlashPlayerState.Normal){
           alert(playerInfo.msg);
        }
    });

//    /**
//    * 注册回调事件
//    * @param {{
//    *       recordEvents:{
//    *         onReady       : Function ,
//    *         onEvalResult  : Function ,
//    *         onRecording   : Function ,
//    *         onAudioLoaded : Function ,
//    *         onPlayStop    : Function ,
//    *         onError       : Function
//    *       },
//    *      playEvents: {
//    *          onStop  : Function
//    *       }
//    *  }} events 事件参数
//    */
    exports.registerEvent = function (events) {
        _recordEvents = events.recordEvents;
        _playEvents = events.playEvents;
    };

    /**
    * 检测麦克风
    * @param {Number} state
    */
    function  setMicrophoneState(state){
        // 没有检测到麦克风
        if (state === MicrophoneState.NotFound) {
            LogUtil.warn("没有检测到麦克风...");
        }
        // 用户拒绝对麦克风访问
        else if (state === MicrophoneState.Denied) {
            LogUtil.warn("请允许使用麦克风！");
            showMicSettings();
        }
        // 用户允许对麦克风访问
        else if (state === MicrophoneState.Allowed) {
            LogUtil.info("麦克风允许使用");
            hideMicSettings();
        }
        else if (state == MicrophoneState.NoEnoughSize) {
            LogUtil.error("没有足够空间显示安全设置面板");
        }
    }

    function showMicSettings() {

        $("#recorder").css({
            width    : '214px',
            height   : '138px',
            top      : $('body').height()/2,
           "margin-left" : navigator.userAgent.indexOf("MSIE")>0 ? 0 : -($('body').width()/8),
            position : 'absolute',
            "z-index":  9999
        });
        _maskOption = {
            type :'fullScreen',
            flag : true
        };
        mask.showMask(_maskOption);
        _speecher.Recorder.showSecuritySettings();
    }

    function hideMicSettings() {
        $("#recorder").css({
            width  : '1px',
            height : '1px'
        });
        if( window.readyInfo.recorder == true && window.readyInfo.player == true){
            _maskOption = {
                type :'fullScreen',
                flag : false
            };
            mask.showMask(_maskOption);
        }
    }

    /**
     * Speecher对象
     * @property
     * @type {Speecher}
     */
    exports.speecher = _speecher;
});

