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;
import tech.starwin.utils.collection.UploadManager;

/**
 * 监听并保存安装referrer
 * 测试发送广播：
 * adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n com.pop.douang/com.components.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) {
        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;
    }
}
