package com.common.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import tech.starwin.constants.ActionEnum;
import tech.starwin.utils.LogUtils;
import tech.starwin.utils.PreferencesManager;

/**
 * 监听并保存安装referrer
 * 测试发送广播：
 * adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n mnsg.dwvc.fiaob.axgywz/com.common.broadcast.InstallReferrerReceiver --es  "referrer" "utm_source=testSource&utm_medium=testMedium&utm_term=testTerm&utm_content=11&PARTNER_ID=111&PARTNER_CLICK_ID=222"
 */

public class InstallReferrerReceiver extends BroadcastReceiver {
    public static String referrer = "";

    public void onReceive(Context context, Intent data) {
        //SDK-CHANNEL-START
//SDK-CHANNEL-CODE	        new com.mixpanel.android.mpmetrics.InstallReferrerReceiver().onReceive(context, data);
//SDK-CHANNEL-CODE	        new com.kochava.base.ReferralReceiver().onReceive(context, data);
//SDK-CHANNEL-CODE	        //SDK-CHANNEL-END
        referrer = getReferrerValue(data.getExtras());
        if (!TextUtils.isEmpty(referrer)) {
            PreferencesManager.get().saveInstallReferrer(referrer);
            EventBus.getDefault().post(ActionEnum.REFERRER_UPDATED);
        }
    }

    private String getReferrerValue(Bundle bundle) {
        String referrerValue = "";

        try {
            if (bundle != null) {
                referrerValue = bundle.getString("referrer");
            }
            if (referrerValue == null) {
                referrerValue = "";
            }

            if (TextUtils.isEmpty(referrerValue)) {
            } else {
            }

        } catch (Exception e) {
            //UploadManager.uploadException(e, "InstallReferrerReceiver.getReferrerValue");
        }

        try {
            referrerValue = URLDecoder.decode(referrerValue, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtils.d("InstallReferrerReceiver", "referrer " + referrerValue);
        return referrerValue;
    }
}
