package com.amazon;

import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;
import com.amazon.inapp.purchasing.BasePurchasingObserver;
import com.amazon.inapp.purchasing.GetUserIdResponse;
import com.amazon.inapp.purchasing.Item;
import com.amazon.inapp.purchasing.ItemDataResponse;
import com.amazon.inapp.purchasing.Offset;
import com.amazon.inapp.purchasing.PurchaseResponse;
import com.amazon.inapp.purchasing.PurchaseUpdatesResponse;
import com.amazon.inapp.purchasing.PurchasingManager;
import com.amazon.inapp.purchasing.Receipt;
import com.tapjoy.TapjoyConstants;
import com.urbanairship.analytics.EventDataManager;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
public class AmazonIAPPlugin extends BasePurchasingObserver {
    public static Activity _activity;
    private static AmazonIAPPlugin _instance;
    private static Field _unityPlayerActivityField;
    private static Class<?> _unityPlayerClass;
    private static Method _unitySendMessageMethod;
    private final String _offsetPrefsKey;

    public static AmazonIAPPlugin instance() {
        if (_instance == null) {
            try {
                _unityPlayerClass = Class.forName("com.unity3d.player.UnityPlayer");
                _unityPlayerActivityField = _unityPlayerClass.getField("currentActivity");
                _unitySendMessageMethod = _unityPlayerClass.getMethod("UnitySendMessage", String.class, String.class, String.class);
            } catch (ClassNotFoundException e) {
                Log.i("Prime31", "could not find UnityPlayer class: " + e.getMessage());
            } catch (NoSuchFieldException e2) {
                Log.i("Prime31", "could not find currentActivity field: " + e2.getMessage());
            } catch (Exception e3) {
                Log.i("Prime31", "unkown exception occurred locating UnityPlayer.currentActivity: " + e3.getMessage());
            }
            _instance = new AmazonIAPPlugin();
        }
        return _instance;
    }

    public AmazonIAPPlugin() {
        super(getActivity());
        this._offsetPrefsKey = "P31Offset";
    }

    private static Activity getActivity() {
        if (_unityPlayerActivityField != null) {
            try {
                return (Activity) _unityPlayerActivityField.get(_unityPlayerClass);
            } catch (Exception e) {
                Log.i("Prime31", "error getting currentActivity: " + e.getMessage());
            }
        }
        return _activity;
    }

    private void UnitySendMessage(String go, String m, String p) {
        if (_unitySendMessageMethod != null) {
            try {
                _unitySendMessageMethod.invoke(null, go, m, p);
                return;
            } catch (IllegalAccessException e) {
                Log.i("Prime31", "could not find UnitySendMessage method: " + e.getMessage());
                return;
            } catch (IllegalArgumentException e2) {
                Log.i("Prime31", "could not find UnitySendMessage method: " + e2.getMessage());
                return;
            } catch (InvocationTargetException e3) {
                Log.i("Prime31", "could not find UnitySendMessage method: " + e3.getMessage());
                return;
            }
        }
        Log.i("Prime31", "UnitySendMessage: " + go + ", " + m + ", " + p);
    }

    public String itemDataResponseToJSON(Set<String> unavailableSkus, Map<String, Item> itemMap) {
        JSONObject root = new JSONObject();
        try {
            JSONArray unavailableArray = new JSONArray();
            for (String sku : unavailableSkus) {
                unavailableArray.put(sku);
            }
            root.put("unavailableSkus", unavailableArray);
            JSONArray availableArray = new JSONArray();
            for (String sku2 : itemMap.keySet()) {
                Item item = itemMap.get(sku2);
                JSONObject obj = new JSONObject();
                obj.put("description", item.getDescription());
                obj.put(EventDataManager.Events.COLUMN_NAME_TYPE, item.getItemType());
                obj.put(TapjoyConstants.TJC_EVENT_IAP_PRICE, item.getPrice());
                obj.put("sku", item.getSku());
                obj.put("smallIconUrl", item.getSmallIconUrl());
                obj.put("title", item.getTitle());
                availableArray.put(obj);
            }
            root.put("availableSkus", availableArray);
            return root.toString();
        } catch (JSONException e) {
            Log.i("Prime31", "error encoding JSON: " + e.getMessage());
            return "{}";
        }
    }

    public String purchaseResponseToJSON(Receipt receipt) {
        JSONObject root = new JSONObject();
        try {
            root.put(EventDataManager.Events.COLUMN_NAME_TYPE, receipt.getItemType());
            root.put("token", receipt.getPurchaseToken());
            root.put("sku", receipt.getSku());
            if (receipt.getItemType() == Item.ItemType.SUBSCRIPTION) {
                root.put("subscriptionStartDate", receipt.getSubscriptionPeriod().getStartDate());
                root.put("subscriptionEndDate", receipt.getSubscriptionPeriod().getEndDate());
            }
            return root.toString();
        } catch (JSONException e) {
            Log.i("Prime31", "error encoding JSON: " + e.getMessage());
            return "";
        }
    }

    public String purchaseUpdateResponseToJSON(Set<String> revokedSkus, Set<Receipt> receipts) {
        JSONObject root = new JSONObject();
        try {
            JSONArray revokedArray = new JSONArray();
            for (String sku : revokedSkus) {
                revokedArray.put(sku);
            }
            root.put("revokedSkus", revokedArray);
            JSONArray receiptArray = new JSONArray();
            for (Receipt receipt : receipts) {
                JSONObject obj = new JSONObject();
                obj.put(EventDataManager.Events.COLUMN_NAME_TYPE, receipt.getItemType());
                obj.put("token", receipt.getPurchaseToken());
                obj.put("sku", receipt.getSku());
                if (receipt.getItemType() == Item.ItemType.SUBSCRIPTION) {
                    obj.put("subscriptionStartDate", receipt.getSubscriptionPeriod().getStartDate());
                    obj.put("subscriptionEndDate", receipt.getSubscriptionPeriod().getEndDate());
                }
                receiptArray.put(obj);
            }
            root.put("receipts", receiptArray);
            return root.toString();
        } catch (JSONException e) {
            Log.i("Prime31", "error encoding JSON: " + e.getMessage());
            return "";
        }
    }

    public void initiateItemDataRequest(String[] items) {
        HashSet<String> itemHash = new HashSet<>(Arrays.asList(items));
        PurchasingManager.registerObserver(this);
        PurchasingManager.initiateItemDataRequest(itemHash);
    }

    public void initiatePurchaseRequest(String sku) {
        PurchasingManager.initiatePurchaseRequest(sku);
    }

    public void initiateGetUserIdRequest() {
        PurchasingManager.initiateGetUserIdRequest();
    }

    public void onItemDataResponse(ItemDataResponse itemDataResponse) {
        if (itemDataResponse.getItemDataRequestStatus() == ItemDataResponse.ItemDataRequestStatus.FAILED) {
            UnitySendMessage("AmazonIAPManager", "itemDataRequestFailed", "");
            return;
        }
        Set<String> unavailableSkus = itemDataResponse.getUnavailableSkus();
        Map<String, Item> itemMap = itemDataResponse.getItemData();
        Log.i("Prime31", "unavilable skus: " + unavailableSkus.size());
        Log.i("Prime31", "available skus: " + itemMap.size());
        String json = itemDataResponseToJSON(unavailableSkus, itemMap);
        UnitySendMessage("AmazonIAPManager", "itemDataRequestFinished", json);
    }

    public void onPurchaseResponse(PurchaseResponse purchaseResponse) {
        if (purchaseResponse.getPurchaseRequestStatus() == PurchaseResponse.PurchaseRequestStatus.FAILED) {
            UnitySendMessage("AmazonIAPManager", "purchaseFailed", "Unknown Reason");
        } else if (purchaseResponse.getPurchaseRequestStatus() == PurchaseResponse.PurchaseRequestStatus.INVALID_SKU) {
            UnitySendMessage("AmazonIAPManager", "purchaseFailed", "Invalid SKU");
        } else if (purchaseResponse.getPurchaseRequestStatus() == PurchaseResponse.PurchaseRequestStatus.ALREADY_ENTITLED) {
            UnitySendMessage("AmazonIAPManager", "purchaseFailed", "Already Entitled");
        } else {
            UnitySendMessage("AmazonIAPManager", "purchaseSuccessful", purchaseResponseToJSON(purchaseResponse.getReceipt()));
        }
    }

    public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse purchaseUpdatesResponse) {
        SharedPreferences prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), 0);
        SharedPreferences.Editor playerPrefs = prefs.edit();
        Offset offset = purchaseUpdatesResponse.getOffset();
        playerPrefs.putString("P31Offset", offset.toString());
        playerPrefs.commit();
        if (purchaseUpdatesResponse.getPurchaseUpdatesRequestStatus() == PurchaseUpdatesResponse.PurchaseUpdatesRequestStatus.FAILED) {
            UnitySendMessage("AmazonIAPManager", "purchaseUpdatesRequestFailed", "");
            return;
        }
        String json = purchaseUpdateResponseToJSON(purchaseUpdatesResponse.getRevokedSkus(), purchaseUpdatesResponse.getReceipts());
        UnitySendMessage("AmazonIAPManager", "purchaseUpdatesRequestSuccessful", json);
    }

    public void onSdkAvailable(boolean isSandboxMode) {
        UnitySendMessage("AmazonIAPManager", "onSdkAvailable", isSandboxMode ? "1" : "0");
        PurchasingManager.initiateGetUserIdRequest();
        SharedPreferences prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), 0);
        String offsetString = prefs.getString("P31Offset", null);
        if (offsetString != null) {
            Log.i("Prime31", "found saved offset: " + offsetString);
        }
        PurchasingManager.initiatePurchaseUpdatesRequest(Offset.fromString(offsetString));
    }

    public void onGetUserIdResponse(GetUserIdResponse getUserIdResponse) {
        UnitySendMessage("AmazonIAPManager", "onGetUserIdResponse", getUserIdResponse.getUserId());
    }
}
