package tech.starwin.utils;

import android.content.Context;
import android.text.TextUtils;

import com.android.installreferrer.api.InstallReferrerClient;
import com.android.installreferrer.api.InstallReferrerStateListener;
import com.android.installreferrer.api.ReferrerDetails;

public class InstallReferrerHelper {

    public static void refershInstallReferrer(Context context) {
        try {
            final InstallReferrerClient installReferrerClient = InstallReferrerClient.newBuilder(context).build();
            installReferrerClient.startConnection(new InstallReferrerStateListener() {
                @Override
                public void onInstallReferrerSetupFinished(int responseCode) {
                    switch (responseCode) {
                        case InstallReferrerClient.InstallReferrerResponse.OK:
                            // Connection established, get referrer
                            if (installReferrerClient != null) {
                                try {
                                    ReferrerDetails response = installReferrerClient.getInstallReferrer();
                                    String referrer = response.getInstallReferrer();
                                    if (!TextUtils.isEmpty(referrer)) {
                                        PreferencesManager.get().saveInstallReferrerFromSDK(referrer);
                                    }
                                    installReferrerClient.endConnection();
                                } catch (Exception ex) {
                                    LogUtils.e("InstallReferrerHelper", ex.toString());
                                }
                            }
                            break;
                        case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
                            // API not available on the current Play Store app
                            LogUtils.d("InstallReferrerHelper", "FEATURE_NOT_SUPPORTED");
                            break;
                        case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE:
                            // Connection could not be established
                            LogUtils.d("InstallReferrerHelper", "SERVICE_UNAVAILABLE");
                            break;
                    }
                }

                @Override
                public void onInstallReferrerServiceDisconnected() {
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                }

            });
        } catch (Exception ex) {
//            LogUtil.e(ex);
            LogUtils.e("InstallReferrerHelper", ex.toString());
        }
    }


}
