package cn.m4399.operateBZ.phx;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;

import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.util.JSUtil;

class Callback {
    private final IWebview iWebview;
    final String id;

    private Callback() {
        iWebview = null;
        id = null;
    }

    Callback(IWebview iWebview, String id) {
        this.iWebview = iWebview;
        this.id = id;
    }

    static Callback optCallback(IWebview iWebview, JSONArray array) {
        try {
            return new Callback(iWebview, array.getString(0));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new Callback();
    }

    // https://www.dcloud.io/docs/sdk/android/io/dcloud/util/JSUtil.html
    void invoke(String msg) {
        invoke(msg, true);
    }

    void invoke(String msg, boolean keepCallback) {
        if (TextUtils.isEmpty(id))
            OperateCenterPHX.androidLog("No callback id retrieved from args");
        else
            JSUtil.execCallback(iWebview, id, msg, JSUtil.OK, keepCallback);
    }
}
