package com.datarecovery.master.sdk.wechat;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.atmob.common.runtime.ContextUtil;
import com.atmob.common.runtime.ProcessUtil;
import com.datarecovery.master.BuildConfig;
import com.datarecovery.master.R;
import com.datarecovery.master.utils.ToastUtil;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WechatHelper {
    private static final String APP_ID = BuildConfig.WECHAT_APP_ID;

    private static final String CROP_ID = BuildConfig.WEWORK_CROP_ID;

    private static final String CUSTOMER_SERVICE_URL = "https://work.weixin.qq.com/kfid/" + BuildConfig.WECHAT_KF_ID;

    private static IWXAPI api;

    static {
        init(ContextUtil.getContext());
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public static void init(Context context) {
        if (!ProcessUtil.isMainProcess(context)) {
            return;
        }
        api = WXAPIFactory.createWXAPI(context, APP_ID, true);
        api.registerApp(APP_ID);
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                api.registerApp(APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
    }

    public static void handleIntent(Intent intent, IWXAPIEventHandler iwxapiEventHandler) {
        if (api == null) {
            throw new IllegalStateException("WechatHelper not init");
        }
        api.handleIntent(intent, iwxapiEventHandler);
    }

    public static void launchCustomerService() {
        if (api == null) {
            throw new IllegalStateException("WechatHelper not init");
        }
        if (api.getWXAppSupportAPI() >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT && api.isWXAppInstalled()) {
            WXOpenCustomerServiceChat.Req req = new WXOpenCustomerServiceChat.Req();
            req.corpId = CROP_ID;
            req.url = CUSTOMER_SERVICE_URL;
            api.sendReq(req);
        } else {
            ToastUtil.show(R.string.wechat_version_too_low_toast, ToastUtil.LENGTH_SHORT);
        }
    }

}