package com.theaimartco.taim;

import com.android.billingclient.api.*;
import org.json.*;
import java.lang.ref.WeakReference;
import java.util.*;

/**
 * Google Play Billing extension (channel {@code taim.billing}). Generated by project.py --billing.
 *
 * Purchases arrive as {@code purchases} events. Verify every purchase token on your server with the
 * Play Developer API before granting entitlement, then acknowledge (or consume) within 3 days or
 * Google refunds it. Client-side state alone is not proof of payment.
 */
public final class TaimBilling implements TaimExtension, TaimPlugin, PurchasesUpdatedListener {
    static final String CHANNEL="taim.billing";
    private WeakReference<TaimActivity> activity=new WeakReference<>(null);
    private BillingClient client;
    private final Map<String,ProductDetails> products=new HashMap<>();

    @Override public void attach(TaimActivity host){
        activity=new WeakReference<>(host);
        client=BillingClient.newBuilder(host.getApplicationContext()).setListener(this)
            .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().enablePrepaidPlans().build())
            .enableAutoServiceReconnection().build(); // Billing 8+: reconnects transparently on SERVICE_DISCONNECTED
        host.registerTaimPlugin(CHANNEL,this);
    }

    private static String code(BillingResult r){
        switch(r.getResponseCode()){
            case BillingClient.BillingResponseCode.OK:return null;
            case BillingClient.BillingResponseCode.USER_CANCELED:return "cancelled";
            case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED:case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE:
            case BillingClient.BillingResponseCode.NETWORK_ERROR:return "unavailable";
            case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE:case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED:return "unsupported";
            case BillingClient.BillingResponseCode.ITEM_UNAVAILABLE:return "notFound";
            case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED:return "busy";
            case BillingClient.BillingResponseCode.DEVELOPER_ERROR:return "invalid";
            default:return "failed";
        }
    }
    private static String type(JSONObject args)throws JSONException{String t=args.getString("type");if(t.equals("inapp"))return BillingClient.ProductType.INAPP;if(t.equals("subs"))return BillingClient.ProductType.SUBS;throw new IllegalArgumentException();}
    private void reply(Result result,BillingResult r,Object value){String c=code(r);if(c==null)result.success(value);else result.error(c);}

    @Override public void call(String method,JSONObject args,Result result){
        try{
            if(method.equals("connect")){
                if(client.isReady()){result.success(null);return;}
                client.startConnection(new BillingClientStateListener(){
                    boolean done;
                    @Override public void onBillingSetupFinished(BillingResult r){if(!done){done=true;reply(result,r,null);}}
                    @Override public void onBillingServiceDisconnected(){if(!done){done=true;result.error("unavailable");}}
                });
                return;
            }
            if(!client.isReady()){result.error("unavailable");return;}
            switch(method){
                case "products":{
                    String type=type(args);JSONArray ids=args.getJSONArray("ids");if(ids.length()==0 || ids.length()>100)throw new IllegalArgumentException();
                    List<QueryProductDetailsParams.Product> list=new ArrayList<>();
                    for(int i=0;i<ids.length();i++)list.add(QueryProductDetailsParams.Product.newBuilder().setProductId(ids.getString(i)).setProductType(type).build());
                    client.queryProductDetailsAsync(QueryProductDetailsParams.newBuilder().setProductList(list).build(),(r,details)->{
                        try{JSONArray out=new JSONArray();for(ProductDetails d:details.getProductDetailsList()){products.put(d.getProductId(),d);out.put(product(d));}reply(result,r,out);}
                        catch(JSONException failed){result.error("failed");}
                    });return;
                }
                case "purchase":{
                    TaimActivity host=activity.get();if(host==null || !host.isTaimResumed()){result.error("cancelledForeground");return;}
                    ProductDetails d=products.get(args.getString("productId"));if(d==null){result.error("notFound");return;}
                    BillingFlowParams.ProductDetailsParams.Builder p=BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(d);
                    if(!args.isNull("offerToken") && args.has("offerToken"))p.setOfferToken(args.getString("offerToken"));
                    else if(d.getProductType().equals(BillingClient.ProductType.SUBS)){result.error("invalid");return;}
                    BillingFlowParams.Builder flow=BillingFlowParams.newBuilder().setProductDetailsParamsList(Collections.singletonList(p.build()));
                    if(args.has("accountId") && !args.isNull("accountId"))flow.setObfuscatedAccountId(args.getString("accountId"));
                    // The result only says whether the sheet opened; the outcome arrives as a purchases event.
                    reply(result,client.launchBillingFlow(host,flow.build()),null);return;
                }
                case "purchases":client.queryPurchasesAsync(QueryPurchasesParams.newBuilder().setProductType(type(args)).build(),(r,list)->{
                    try{reply(result,r,purchases(list));}catch(JSONException failed){result.error("failed");}
                });return;
                case "acknowledge":client.acknowledgePurchase(AcknowledgePurchaseParams.newBuilder().setPurchaseToken(args.getString("token")).build(),r->reply(result,r,null));return;
                case "consume":client.consumeAsync(ConsumeParams.newBuilder().setPurchaseToken(args.getString("token")).build(),(r,token)->reply(result,r,null));return;
                default:result.error("invalid");
            }
        }catch(JSONException | IllegalArgumentException bad){result.error("invalid");}
    }

    @Override public void onPurchasesUpdated(BillingResult r,List<Purchase> list){
        TaimActivity host=activity.get();if(host==null)return; // unacknowledged purchases are re-queried on next launch
        try{
            String c=code(r);
            host.emitTaimPluginEvent(CHANNEL,new JSONObject().put("type","purchases").put("result",c==null?"ok":c).put("purchases",purchases(list==null?Collections.emptyList():list)));
        }catch(JSONException ignored){}
    }

    private static JSONArray purchases(List<Purchase> list)throws JSONException{
        JSONArray out=new JSONArray();
        for(Purchase p:list){
            int s=p.getPurchaseState();
            out.put(new JSONObject().put("orderId",p.getOrderId()==null?JSONObject.NULL:p.getOrderId()).put("products",new JSONArray(p.getProducts()))
                .put("token",p.getPurchaseToken()).put("state",s==Purchase.PurchaseState.PURCHASED?"purchased":s==Purchase.PurchaseState.PENDING?"pending":"unspecified")
                .put("acknowledged",p.isAcknowledged()).put("autoRenewing",p.isAutoRenewing()).put("timeMs",p.getPurchaseTime()).put("quantity",p.getQuantity())
                .put("originalJson",p.getOriginalJson()).put("signature",p.getSignature()));
        }
        return out;
    }
    private static JSONObject price(long micros,String formatted,String currency)throws JSONException{return new JSONObject().put("micros",micros).put("formatted",formatted).put("currency",currency);}
    private static JSONObject product(ProductDetails d)throws JSONException{
        JSONObject out=new JSONObject().put("id",d.getProductId()).put("type",d.getProductType().equals(BillingClient.ProductType.SUBS)?"subs":"inapp")
            .put("title",d.getTitle()).put("name",d.getName()).put("description",d.getDescription());
        ProductDetails.OneTimePurchaseOfferDetails one=d.getOneTimePurchaseOfferDetails();
        out.put("price",one==null?JSONObject.NULL:price(one.getPriceAmountMicros(),one.getFormattedPrice(),one.getPriceCurrencyCode()));
        JSONArray offers=new JSONArray();
        if(d.getSubscriptionOfferDetails()!=null)for(ProductDetails.SubscriptionOfferDetails o:d.getSubscriptionOfferDetails()){
            JSONArray phases=new JSONArray();
            for(ProductDetails.PricingPhase ph:o.getPricingPhases().getPricingPhaseList())
                phases.put(price(ph.getPriceAmountMicros(),ph.getFormattedPrice(),ph.getPriceCurrencyCode()).put("period",ph.getBillingPeriod()).put("cycles",ph.getBillingCycleCount()));
            offers.put(new JSONObject().put("token",o.getOfferToken()).put("basePlanId",o.getBasePlanId()).put("offerId",o.getOfferId()==null?JSONObject.NULL:o.getOfferId()).put("phases",phases));
        }
        return out.put("offers",offers);
    }

    @Override public void detach(){if(client!=null)client.endConnection();}
}
