/**
 * Created by jhwang on 14-10-13.
 * User: haozes
 * Date: 1-7-24
 * Time: 上午8:44
 * ios 与 webview 交互的通道
 */
define(function(require, exports) {
    var Hashtable = require('./hashtable').Hashtable;

    var cbkArr = new Hashtable();

    function genId(){
        return (Math.random()*100000000000000000).toString();
    }

    /***
     * 执行ios方法的方法
     * @param method    方法名
     * @param args      参数(必须要传一个字符串，哪怕是空的都行)
     * @param iskeepLive   是否执行完还保留回调，true保留（可能会内存泄露），默认设置为false
     * @param callbck       异步回调
     */
    function execute(method, args, iskeepLive, callbck) {
        //console.log(cls, method, args, iskeepLive, callbck);

        var cbkId = genId();
        if (iskeepLive) {
            cbkId = 'k' + cbkId;
        }
        cbkArr.add(cbkId, callbck);
        var message={"method":method,"args":args,"cbkid":cbkId};
        //AndroidJsHandler.execute(method, args, cbkId);
        window.webkit.messageHandlers.interOp.postMessage(message);
    }

    function onInvoked(callbackId, err, ret) {
        //console.log('onInvoked',callbackId,err,ret);
        var cbk = cbkArr.get(callbackId);
        if (cbk) {
            cbk(err, ret);
            if (callbackId[0] != 'k') {
                cbkArr.remove(callbackId);
            }
        }
    }

    exports.execute = execute;
    exports.onInvoked = onInvoked;
    // 注册到全局变量中去
    if (!window.IOSSink) {
        window.IOSSink = exports;
    }

});

