package tech.starwin.broadcast;

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

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

import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.collection.UploadManager;

/**
 * 监听并保存安装referrer
 * 测试方法：
 * 1 进到adb shell
 * 2 打开GAv4的log：setprop log.tag.GAv4 VERBOSE
 * 3 发送广播通知：
 * am broadcast -a com.android.vending.INSTALL_REFERRER -n com.mango.cash/com.daunkredit.program
 * .sulu.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 install_referrer_store_key = "GA_install_referrer_store_key";

    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();
        }
        Log.i("InstallReferrerReceiver", "referrer " + referrerValue);
        return referrerValue;
    }
}
