package com.urbanairship.iap;

import android.app.Activity;
import com.urbanairship.Logger;
import com.urbanairship.UAirship;
import com.urbanairship.iap.Product;
import com.urbanairship.restclient.AppAuthenticatedRequest;
import com.urbanairship.restclient.AsyncHandler;
import com.urbanairship.restclient.Response;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.TreeMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
public class Inventory {
    private Map<String, Product> products = new TreeMap();
    private ArrayList<Product> allProducts = new ArrayList<>();
    private ArrayList<Product> updatedProducts = new ArrayList<>();
    private ArrayList<Product> installedProducts = new ArrayList<>();
    private Status status = Status.INITIALIZED;
    private InventoryObservable notifier = new InventoryObservable();

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public enum FilterType {
        ALL,
        INSTALLED,
        UPDATED
    }

    /* 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 InventoryObservable extends Observable {
        private InventoryObservable() {
        }

        @Override // java.util.Observable
        public void notifyObservers(Object obj) {
            setChanged();
            super.notifyObservers(obj);
        }
    }

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public enum Status {
        INITIALIZED,
        DOWNLOADING,
        LOADED,
        FAILED,
        EMPTY
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void setProducts(JSONArray jSONArray) throws JSONException {
        for (int i = 0; i < jSONArray.length(); i++) {
            Product product = new Product(jSONArray.getJSONObject(i));
            this.products.put(product.getIdentifier(), product);
        }
    }

    public void addObserver(Observer observer) {
        this.notifier.addObserver(observer);
    }

    public void deleteObserver(Observer observer) {
        this.notifier.deleteObserver(observer);
    }

    public Product getProduct(String str) {
        return this.products.get(str);
    }

    public List<Product> getProducts(FilterType filterType) {
        ArrayList<Product> arrayList = null;
        switch (filterType) {
            case ALL:
                arrayList = this.allProducts;
                break;
            case INSTALLED:
                arrayList = this.installedProducts;
                break;
            case UPDATED:
                arrayList = this.updatedProducts;
                break;
            default:
                Logger.error("No product list for " + filterType);
                break;
        }
        return Collections.unmodifiableList(arrayList);
    }

    public Status getStatus() {
        return this.status;
    }

    public boolean hasProduct(String str) {
        return this.products.containsKey(str);
    }

    public void load() {
        if (!UAirship.shared().isFlying()) {
            throw new UnsupportedOperationException("Inventory cannot be loaded unless UAirship.takeOff() has been called");
        }
        Logger.info("Loading inventory");
        String str = UAirship.shared().getAirshipConfigOptions().hostURL + "api/app/content/?platform=android";
        Logger.info("Fetching inventory from: " + str);
        new AppAuthenticatedRequest("GET", str).executeAsync(new AsyncHandler() { // from class: com.urbanairship.iap.Inventory.1
            @Override // com.urbanairship.restclient.AsyncHandler
            public void onComplete(Response response) {
                if (response.status() != 200) {
                    if (response.status() == 401) {
                        Logger.error("Authorization failed, make sure the application key and secret are propertly set");
                    }
                    Logger.info("inventoryRequest response status: " + response.status());
                    Logger.info("inventoryRequest response string: " + response.body());
                    Inventory.this.setStatus(Status.FAILED);
                    return;
                }
                String body = response.body();
                try {
                    Logger.info("Inventory response string: " + body);
                    Inventory.this.setProducts((JSONArray) new JSONTokener(body).nextValue());
                } catch (Exception e) {
                    Logger.error("Error parsing JSON product list");
                    Inventory.this.setStatus(Status.FAILED);
                }
                Inventory.this.refresh();
                if (Inventory.this.getStatus() == Status.LOADED) {
                    Logger.info("Inventory loaded " + Inventory.this.allProducts);
                }
            }

            @Override // com.urbanairship.restclient.AsyncHandler
            public void onError(Exception exc) {
                Logger.error("Error loading product inventory from server");
                Inventory.this.setStatus(Status.FAILED);
            }
        });
        setStatus(Status.DOWNLOADING);
    }

    public void purchase(Activity activity, Product product) {
        String identifier = product.getIdentifier();
        String title = product.getTitle();
        if (this.status != Status.LOADED) {
            return;
        }
        Logger.info("Retrieving product: " + title);
        if (product.isFree() || product.getStatus() == Product.Status.UPDATE) {
            Logger.info("Free or updated product, will download if valid...");
            if (Receipt.contains(product.getIdentifier())) {
                Receipt fetch = Receipt.fetch(identifier);
                fetch.setProductRevision(Integer.valueOf(product.getRevision()));
                fetch.serialize();
            } else {
                new Receipt(Integer.valueOf(product.getRevision()), product.getIdentifier()).serialize();
            }
            IAPManager.shared().getDownloadManager().downloadIfValid(product);
        } else if (activity == null) {
            Logger.warn("Attempting to purchase product with null activity parameter, bailing");
        } else {
            Logger.info("Paid product, attempting to purchase: [" + product.getIdentifier() + "] " + product.getTitle());
            product.setStatus(Product.Status.WAITING);
            if (IAPManager.shared().payForProduct(activity, product)) {
                return;
            }
            product.setStatus(Product.Status.UNPURCHASED);
        }
    }

    void purchase(Activity activity, String str) {
        purchase(activity, getProduct(str));
    }

    void refresh() {
        Logger.info("Updating inventory");
        this.allProducts.clear();
        this.allProducts.addAll(this.products.values());
        Collections.sort(this.allProducts);
        this.updatedProducts.clear();
        this.installedProducts.clear();
        Iterator<Product> it = this.allProducts.iterator();
        while (it.hasNext()) {
            Product next = it.next();
            if (next.getStatus() == Product.Status.UPDATE) {
                this.updatedProducts.add(next);
            }
            if (next.getStatus() == Product.Status.PURCHASED || next.getStatus() == Product.Status.DOWNLOADING || next.getStatus() == Product.Status.INSTALLED) {
                this.installedProducts.add(next);
            }
        }
        if (this.allProducts.size() > 0) {
            setStatus(Status.LOADED);
        } else {
            setStatus(Status.EMPTY);
        }
    }

    void setStatus(Status status) {
        this.status = status;
        this.notifier.notifyObservers(this);
    }

    public int size(FilterType filterType) {
        switch (filterType) {
            case ALL:
                return this.allProducts.size();
            case INSTALLED:
                return this.installedProducts.size();
            case UPDATED:
                return this.updatedProducts.size();
            default:
                Logger.error("No product list for " + filterType);
                return 0;
        }
    }
}
