package com.urbanairship.iap.marketinterface;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.BadParcelableException;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import com.android.vending.billing.IMarketBillingService;
import com.urbanairship.Logger;
import com.urbanairship.iap.marketinterface.Consts;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
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/2.dex */
public class BillingService extends Service implements ServiceConnection {
    private static LinkedList<BillingRequest> mPendingRequests = new LinkedList<>();
    private static HashMap<Long, BillingRequest> mSentRequests = new HashMap<>();
    private static IMarketBillingService mService;

    /* JADX INFO: Access modifiers changed from: package-private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public abstract class BillingRequest {
        protected long mRequestId;
        private final int mStartId;

        public BillingRequest(int i) {
            this.mStartId = i;
        }

        public int getStartId() {
            return this.mStartId;
        }

        protected void logResponseCode(String str, Bundle bundle) {
            Consts.ResponseCode.valueOf(bundle.getInt("RESPONSE_CODE"));
        }

        protected Bundle makeRequestBundle(String str) {
            Bundle bundle = new Bundle();
            bundle.putString(Consts.BILLING_REQUEST_METHOD, str);
            bundle.putInt(Consts.BILLING_REQUEST_API_VERSION, 1);
            bundle.putString(Consts.BILLING_REQUEST_PACKAGE_NAME, BillingService.this.getPackageName());
            return bundle;
        }

        protected void onRemoteException(RemoteException remoteException) {
            Logger.warn("remote billing service crashed");
            IMarketBillingService unused = BillingService.mService = null;
        }

        protected void responseCodeReceived(Consts.ResponseCode responseCode) {
        }

        protected abstract long run() throws RemoteException;

        public boolean runIfConnected() {
            if (BillingService.mService != null) {
                try {
                    this.mRequestId = run();
                    if (this.mRequestId >= 0) {
                        BillingService.mSentRequests.put(Long.valueOf(this.mRequestId), this);
                    }
                    return true;
                } catch (RemoteException e) {
                    onRemoteException(e);
                }
            }
            return false;
        }

        public boolean runRequest() {
            if (runIfConnected()) {
                return true;
            }
            if (BillingService.this.bindToMarketBillingService()) {
                BillingService.mPendingRequests.add(this);
                return true;
            }
            return false;
        }

        public Bundle send(Bundle bundle) throws MarketFailException, RemoteException {
            try {
                return BillingService.mService.sendBillingRequest(bundle);
            } catch (BadParcelableException e) {
                Logger.error("BadParcelableException sending billing request: " + e.getMessage());
                throw new MarketFailException("Failure sending billing request");
            } catch (IllegalArgumentException e2) {
                Logger.error("IllegalArgumentException sending billing request: " + e2.getMessage());
                throw new MarketFailException("Failure sending billing request");
            } catch (IllegalStateException e3) {
                Logger.error("IllegalStateException sending billing request: " + e3.getMessage());
                throw new MarketFailException("Failure sending billing request");
            } catch (NullPointerException e4) {
                Logger.error("NullPointerException sending billing request: " + e4.getMessage());
                throw new MarketFailException("Failure sending billing request");
            } catch (SecurityException e5) {
                Logger.error("SecurityException sending billing request: " + e5.getMessage());
                throw new MarketFailException("Failure sending billing request");
            } catch (RuntimeException e6) {
                Logger.error("RuntimeException sending billing request: " + e6.getMessage());
                throw new MarketFailException("Failure sending billing request");
            } catch (Exception e7) {
                Logger.error("Unknown exception sending billing request: " + e7.getMessage());
                throw new MarketFailException("Failure sending billing request");
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class CheckBillingSupported extends BillingRequest {
        public CheckBillingSupported() {
            super(-1);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected long run() throws RemoteException {
            try {
                Bundle send = send(makeRequestBundle("CHECK_BILLING_SUPPORTED"));
                ResponseHandler.checkBillingSupportedResponse(send.getInt("RESPONSE_CODE") == Consts.ResponseCode.RESULT_OK.ordinal());
                return send.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
            } catch (MarketFailException e) {
                Logger.warn("checkBillingSupported failed");
                ResponseHandler.checkBillingSupportedResponse(false);
                return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class ConfirmNotifications extends BillingRequest {
        final String[] mNotifyIds;

        public ConfirmNotifications(int i, String[] strArr) {
            super(i);
            this.mNotifyIds = strArr;
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected long run() throws RemoteException {
            Bundle makeRequestBundle = makeRequestBundle("CONFIRM_NOTIFICATIONS");
            makeRequestBundle.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, this.mNotifyIds);
            try {
                Bundle send = send(makeRequestBundle);
                logResponseCode("confirmNotifications", send);
                return send.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
            } catch (MarketFailException e) {
                Logger.warn("confirmNotifications failed");
                return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class GetPurchaseInformation extends BillingRequest {
        long mNonce;
        final String[] mNotifyIds;

        public GetPurchaseInformation(int i, String[] strArr) {
            super(i);
            this.mNotifyIds = strArr;
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected void onRemoteException(RemoteException remoteException) {
            super.onRemoteException(remoteException);
            Security.removeNonce(this.mNonce);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected long run() throws RemoteException {
            this.mNonce = Security.generateNonce();
            Bundle makeRequestBundle = makeRequestBundle("GET_PURCHASE_INFORMATION");
            makeRequestBundle.putLong(Consts.BILLING_REQUEST_NONCE, this.mNonce);
            makeRequestBundle.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, this.mNotifyIds);
            try {
                Bundle send = send(makeRequestBundle);
                logResponseCode("getPurchaseInformation", send);
                return send.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
            } catch (MarketFailException e) {
                Logger.warn("getPurchaseInformation failed");
                return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class MarketFailException extends Exception {
        private static final long serialVersionUID = 1;

        public MarketFailException(String str) {
            super(str);
        }
    }

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class Purchase {
        public String developerPayload;
        public String notificationId;
        public String orderId;
        public String productId;
        public Consts.PurchaseState purchaseState;
        public long purchaseTime;

        public Purchase(Consts.PurchaseState purchaseState, String str, String str2, String str3, long j, String str4) {
            this.purchaseState = purchaseState;
            this.notificationId = str;
            this.productId = str2;
            this.orderId = str3;
            this.purchaseTime = j;
            this.developerPayload = str4;
        }
    }

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class RequestPurchase extends BillingRequest {
        public final Activity activity;
        public final String mDeveloperPayload;
        public final String mProductId;

        public RequestPurchase(BillingService billingService, Activity activity, String str) {
            this(activity, str, null);
        }

        public RequestPurchase(Activity activity, String str, String str2) {
            super(-1);
            this.mProductId = str;
            this.mDeveloperPayload = str2;
            this.activity = activity;
            Logger.debug("Request Purchase for: " + str);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ int getStartId() {
            return super.getStartId();
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected void responseCodeReceived(Consts.ResponseCode responseCode) {
            ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected long run() throws RemoteException {
            Bundle makeRequestBundle = makeRequestBundle("REQUEST_PURCHASE");
            makeRequestBundle.putString(Consts.BILLING_REQUEST_ITEM_ID, this.mProductId);
            if (this.mDeveloperPayload != null) {
                makeRequestBundle.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, this.mDeveloperPayload);
            }
            try {
                Bundle send = send(makeRequestBundle);
                PendingIntent pendingIntent = (PendingIntent) send.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
                if (pendingIntent == null) {
                    Logger.error("Error with requestPurchase");
                    return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
                }
                ResponseHandler.buyPageIntentResponse(this.activity, pendingIntent, new Intent());
                return send.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
            } catch (MarketFailException e) {
                Logger.warn("requestPurchase failed");
                return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
            }
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ boolean runIfConnected() {
            return super.runIfConnected();
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ boolean runRequest() {
            return super.runRequest();
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ Bundle send(Bundle bundle) throws MarketFailException, RemoteException {
            return super.send(bundle);
        }
    }

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class RestoreTransactions extends BillingRequest {
        long mNonce;

        public RestoreTransactions() {
            super(-1);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ int getStartId() {
            return super.getStartId();
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected void onRemoteException(RemoteException remoteException) {
            super.onRemoteException(remoteException);
            Security.removeNonce(this.mNonce);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected void responseCodeReceived(Consts.ResponseCode responseCode) {
            ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        protected long run() throws RemoteException {
            this.mNonce = Security.generateNonce();
            Bundle makeRequestBundle = makeRequestBundle("RESTORE_TRANSACTIONS");
            makeRequestBundle.putLong(Consts.BILLING_REQUEST_NONCE, this.mNonce);
            try {
                Bundle send = send(makeRequestBundle);
                logResponseCode("restoreTransactions", send);
                return send.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
            } catch (MarketFailException e) {
                Logger.warn("resoreTransactions failed");
                return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
            }
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ boolean runIfConnected() {
            return super.runIfConnected();
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ boolean runRequest() {
            return super.runRequest();
        }

        @Override // com.urbanairship.iap.marketinterface.BillingService.BillingRequest
        public /* bridge */ /* synthetic */ Bundle send(Bundle bundle) throws MarketFailException, RemoteException {
            return super.send(bundle);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean bindToMarketBillingService() {
        try {
        } catch (SecurityException e) {
            Logger.error("Security exception: " + e);
        }
        if (bindService(new Intent(Consts.MARKET_BILLING_SERVICE_ACTION), this, 1)) {
            return true;
        }
        Logger.error("Could not bind to service.");
        return false;
    }

    private void checkResponseCode(long j, Consts.ResponseCode responseCode) {
        BillingRequest billingRequest = mSentRequests.get(Long.valueOf(j));
        if (billingRequest != null) {
            billingRequest.responseCodeReceived(responseCode);
        }
        mSentRequests.remove(Long.valueOf(j));
    }

    private boolean confirmNotifications(int i, String[] strArr) {
        return new ConfirmNotifications(i, strArr).runRequest();
    }

    private boolean getPurchaseInformation(int i, String[] strArr) {
        return new GetPurchaseInformation(i, strArr).runRequest();
    }

    private ArrayList<Purchase> getPurchases(String str, String str2) {
        ArrayList<Purchase> arrayList = new ArrayList<>();
        try {
            JSONArray optJSONArray = new JSONObject(str).optJSONArray("orders");
            int length = optJSONArray != null ? optJSONArray.length() : 0;
            for (int i = 0; i < length; i++) {
                try {
                    JSONObject jSONObject = optJSONArray.getJSONObject(i);
                    arrayList.add(new Purchase(Consts.PurchaseState.valueOf(jSONObject.getInt("purchaseState")), jSONObject.has("notificationId") ? jSONObject.getString("notificationId") : null, jSONObject.getString("productId"), jSONObject.optString("orderId", ""), jSONObject.getLong("purchaseTime"), jSONObject.optString("developerPayload", null)));
                } catch (JSONException e) {
                    Logger.error("JSON exception: ", e);
                    return null;
                }
            }
            return arrayList;
        } catch (JSONException e2) {
            return null;
        }
    }

    private void purchaseStateChanged(int i, String str, String str2) {
        ArrayList<Purchase> purchases = getPurchases(str, str2);
        if (purchases == null) {
            return;
        }
        ArrayList arrayList = new ArrayList();
        Iterator<Purchase> it = purchases.iterator();
        while (it.hasNext()) {
            Purchase next = it.next();
            if (next.notificationId != null) {
                arrayList.add(next.notificationId);
            }
            ResponseHandler.purchaseResponse(next.purchaseState, next.productId, next.orderId, next.purchaseTime, str, str2);
        }
        if (arrayList.isEmpty()) {
            return;
        }
        confirmNotifications(i, (String[]) arrayList.toArray(new String[arrayList.size()]));
    }

    private void runPendingRequests() {
        int i = -1;
        while (true) {
            BillingRequest peek = mPendingRequests.peek();
            if (peek == null) {
                if (i >= 0) {
                    stopSelf(i);
                    return;
                }
                return;
            }
            Logger.verbose("Billing Service - running request: " + peek.getStartId());
            if (!peek.runIfConnected()) {
                Logger.debug("Billing Service - bind to market service");
                bindToMarketBillingService();
                return;
            }
            Logger.verbose("Billing Service - request ran: " + peek.getStartId());
            mPendingRequests.remove();
            if (i < peek.getStartId()) {
                i = peek.getStartId();
            }
        }
    }

    public boolean checkBillingSupported() {
        return new CheckBillingSupported().runRequest();
    }

    public void handleCommand(Intent intent, int i) {
        String action = intent.getAction();
        if (Consts.ACTION_CONFIRM_NOTIFICATION.equals(action)) {
            confirmNotifications(i, intent.getStringArrayExtra(Consts.NOTIFICATION_ID));
        } else if (Consts.ACTION_GET_PURCHASE_INFORMATION.equals(action)) {
            getPurchaseInformation(i, new String[]{intent.getStringExtra(Consts.NOTIFICATION_ID)});
        } else if (!Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
            if (Consts.ACTION_RESPONSE_CODE.equals(action)) {
                checkResponseCode(intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1L), Consts.ResponseCode.valueOf(intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, Consts.ResponseCode.RESULT_ERROR.ordinal())));
            }
        } else {
            String stringExtra = intent.getStringExtra(Consts.INAPP_SIGNED_DATA);
            String stringExtra2 = intent.getStringExtra(Consts.INAPP_SIGNATURE);
            if (stringExtra != null && stringExtra2 != null) {
                purchaseStateChanged(i, stringExtra, stringExtra2);
                return;
            }
            Logger.warn("Received purchaseStateChanged intent with null signature/data!");
            Logger.warn("Purchase not verified!");
        }
    }

    @Override // android.app.Service
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override // android.content.ServiceConnection
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        mService = IMarketBillingService.Stub.asInterface(iBinder);
        runPendingRequests();
    }

    @Override // android.content.ServiceConnection
    public void onServiceDisconnected(ComponentName componentName) {
        Logger.warn("Billing service disconnected");
        mService = null;
    }

    @Override // android.app.Service
    public void onStart(Intent intent, int i) {
        if (intent != null) {
            handleCommand(intent, i);
        }
    }

    public boolean requestPurchase(Activity activity, String str) {
        return new RequestPurchase(this, activity, str).runRequest();
    }

    public boolean requestPurchase(Activity activity, String str, String str2) {
        return new RequestPurchase(activity, str, str2).runRequest();
    }

    public boolean restoreTransactions() {
        return new RestoreTransactions().runRequest();
    }

    public void setContext(Context context) {
        attachBaseContext(context);
    }

    public void unbind() {
        try {
            unbindService(this);
        } catch (IllegalArgumentException e) {
        }
    }
}
