package io.branch.referral;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

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

/**
 * <p> Class for listening installation referrer params. Add this class to your manifest in order to get a referrer info </p>
 * <p>
 * <p> Add to InstallListener to manifest as follows
 * <!--   <receiver android:name="io.branch.referral.InstallListener" android:exported="true">
 * <intent-filter>
 * <action android:name="com.android.vending.INSTALL_REFERRER" />
 * </intent-filter>
 * </receiver> -->
 * </p>
 */
public class InstallListener extends BroadcastReceiver {

    /* Link identifier on installing app from play store. */
    private static String installID_ = PrefHelper.NO_STRING_VALUE;
    private static IInstallReferrerEvents callback_ = null;


    private static boolean isWaitingForReferrer;
    // PRS : In case play store referrer get reported really fast as google fix bugs , this implementation will let the referrer parsed and stored
    //       This will be reported when SDK ask for it
    private static boolean unReportedReferrerAvailable;

    public static void captureInstallReferrer(final long maxWaitTime) {
        if (unReportedReferrerAvailable) {
            reportInstallReferrer();
        } else {
            isWaitingForReferrer = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    reportInstallReferrer();
                }
            }, maxWaitTime);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String rawReferrerString = intent.getStringExtra("referrer");
        if (rawReferrerString != null) {
            try {
                rawReferrerString = URLDecoder.decode(rawReferrerString, "UTF-8");
                HashMap<String, String> referrerMap = new HashMap<>();
                String[] referralParams = rawReferrerString.split("&");

                for (String referrerParam : referralParams) {
                    String[] keyValue = referrerParam.split("=");
                    if (keyValue.length > 1) { // To make sure that there is one key value pair in referrer
                        referrerMap.put(URLDecoder.decode(keyValue[0], "UTF-8"), URLDecoder.decode(keyValue[1], "UTF-8"));
                    }
                }

                PrefHelper prefHelper = PrefHelper.getInstance(context);

                if (referrerMap.containsKey(Defines.Jsonkey.LinkClickID.getKey())) {
                    installID_ = referrerMap.get(Defines.Jsonkey.LinkClickID.getKey());
                    prefHelper.setLinkClickIdentifier(installID_);

                }
                // Check for full app conversion
                if (referrerMap.containsKey(Defines.Jsonkey.IsFullAppConv.getKey())
                        && referrerMap.containsKey(Defines.Jsonkey.ReferringLink.getKey())) {
                    prefHelper.setIsFullAppConversion(Boolean.parseBoolean(referrerMap.get(Defines.Jsonkey.IsFullAppConv.getKey())));
                    prefHelper.setAppLink(referrerMap.get(Defines.Jsonkey.ReferringLink.getKey()));
                }

                if (referrerMap.containsKey(Defines.Jsonkey.GoogleSearchInstallReferrer.getKey())) {
                    prefHelper.setGoogleSearchInstallIdentifier(referrerMap.get(Defines.Jsonkey.GoogleSearchInstallReferrer.getKey()));
                    prefHelper.setGooglePlayReferrer(rawReferrerString);
                }
                unReportedReferrerAvailable = true;

                if (isWaitingForReferrer) {
                    reportInstallReferrer();
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                Log.w("BranchSDK", "Illegal characters in url encoded string");
            }

        }
    }

    public static String getInstallationID() {
        return installID_;
    }

    private static void reportInstallReferrer() {
        if (callback_ != null) {
            callback_.onInstallReferrerEventsFinished();
            callback_ = null;
            unReportedReferrerAvailable = false;
        }
    }

    public static void setListener(IInstallReferrerEvents installReferrerFetch) {
        callback_ = installReferrerFetch;
    }

    interface IInstallReferrerEvents {
        void onInstallReferrerEventsFinished();
    }


}

@@ -150,24 +150,55 @@
 os.Handler;%0A
+import android.text.TextUtils;%0A
 import andro
@@ -210,16 +210,16 @@
 il.Log;%0A
-
 %0Aimport 
@@ -789,17 +789,21 @@
 eiver %7B%0A
+    
 %0A
-
     /* L
@@ -982,17 +982,25 @@
 = null;%0A
-%0A
+    %0A    
 %0A    pri
@@ -1299,17 +1299,21 @@
 ilable;%0A
+    
 %0A
-
     publ
@@ -1735,25 +1735,29 @@
     %7D%0A    %7D%0A
+    
 %0A
-
     @Overrid
@@ -2173,17 +2173,33 @@
 t(%22&%22);%0A
+                
 %0A
-
         
@@ -2248,24 +2248,297 @@
 alParams) %7B%0A
+                    if (!TextUtils.isEmpty(referrerParam)) %7B%0A                        String splitter = %22=%22;%0A                        if (!referrerParam.contains(%22=%22) && referrerParam.contains(%22-%22)) %7B%0A                            splitter = %22-%22;%0A                        %7D%0A    
             
@@ -2589,14 +2589,23 @@
 lit(
-%22=%22);%0A
+splitter);%0A    
     
@@ -2732,16 +2732,20 @@
         
+    
 referrer
@@ -2831,24 +2831,50 @@
  %22UTF-8%22));%0A
+                        %7D%0A
             
@@ -2893,33 +2893,49 @@
               %7D%0A
+                
 %0A
-
                 
@@ -2991,17 +2991,33 @@
 ntext);%0A
+                
 %0A
-
         
@@ -3248,17 +3248,37 @@
 llID_);%0A
+                    
 %0A
-
         
@@ -3758,33 +3758,49 @@
               %7D%0A
+                
 %0A
-
                 
@@ -4163,17 +4163,33 @@
 = true;%0A
+                
 %0A
-
         
@@ -4279,33 +4279,49 @@
               %7D%0A
+                
 %0A
-
             %7D ca
@@ -4574,25 +4574,37 @@
           %7D%0A
+            
 %0A
-
         %7D%0A  
@@ -4599,33 +4599,37 @@
         %7D%0A    %7D%0A
+    
 %0A
-
     public stati
@@ -4688,25 +4688,29 @@
 lID_;%0A    %7D%0A
+    
 %0A
-
     private 
@@ -4928,25 +4928,29 @@
     %7D%0A    %7D%0A
+    
 %0A
-
     public s
@@ -5067,17 +5067,21 @@
 ;%0A    %7D%0A
+    
 %0A
-
     inte
@@ -5165,12 +5165,20 @@
 ;%0A    %7D%0A
-%0A
+    %0A    
 %0A%7D%0A

Fix for referrer kv issue on Android 6.0