/**
 * Created with JetBrains WebStorm.
 * User: haozes
 * Date: 1-7-24
 * Time: 上午8:44
 * android 与 webview 交互的通道
 */
define(function(require, exports) {
    var Hashtable = require('./hashtable').Hashtable;

    var cbkArr = new Hashtable();

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

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

        var cbkId = genId();
        if (iskeepLive) {
            cbkId = 'k' + cbkId;
        }
        cbkArr.add(cbkId, callbck);
        AndroidJsHandler.execute(cls, method, args, cbkId);
    }

    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.androidSink) {
        window.androidSink = exports;
    }

});

