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 java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

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

/**
 * 监听并保存安装referrer
 * 测试发送广播：
 * adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n evskp.rojtuy.ocelng.dczo/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 void onReceive(Context context, Intent data) {
//        new com.kochava.base.ReferralReceiver().onReceive(context, data);
        PreferencesManager.get().saveInstallReferrer(getReferrerValue(data.getExtras()));
    }

    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;
    }
}
