package app.fedilab.fedilabtube.drawable;
/* Copyright 2021 Thomas Schneider
 *
 * This file is a part of TubeLab
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with TubeLab; if not,
 * see <http://www.gnu.org/licenses>. */

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.databinding.DrawerMyDonationBinding;
import es.dmoral.toasty.Toasty;


public class DonationHistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final List<SkuDetails> skuDetailsList;
    private final BillingClient billingClient;
    private Context context;
    private final HashMap<String, Purchase> map;

    public DonationHistoryAdapter(List<SkuDetails> SkuDetailsList, HashMap<String, Purchase> map, BillingClient billingClient) {
        this.skuDetailsList = SkuDetailsList;
        this.billingClient = billingClient;
        this.map = map;
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();
        DrawerMyDonationBinding itemBinding = DrawerMyDonationBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(itemBinding);

    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        final ViewHolder holder = (ViewHolder) viewHolder;
        SkuDetails skuDetails = skuDetailsList.get(position);
        holder.binding.productTitle.setText(skuDetails.getTitle());
        holder.binding.productName.setText(skuDetails.getDescription());
        holder.binding.productInfo.setText(skuDetails.getOriginalPrice());

        holder.binding.cancelDonation.setOnClickListener(v -> {

            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
            dialogBuilder.setMessage(R.string.cancel_subscription_confirm);

            dialogBuilder.setPositiveButton(R.string.cancel_subscription, (dialog, id) -> {
                JSONObject skudetailsJson;
                try {
                    skudetailsJson = new JSONObject(skuDetails.getOriginalJson());
                    String productId = skudetailsJson.getString("productId");
                    if (map.containsKey(productId)) {
                        Purchase purchase = map.get(productId);
                        if (purchase != null) {
                            ConsumeParams consumeParams =
                                    ConsumeParams.newBuilder()
                                            .setPurchaseToken(purchase.getPurchaseToken())
                                            .build();
                            if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                                ConsumeResponseListener listener = (billingResult1, purchaseToken) -> {
                                    if (billingResult1.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                                        Toasty.success(context, context.getString(R.string.subscription_cancelled), Toasty.LENGTH_LONG).show();
                                    }
                                    skuDetailsList.remove(skuDetails);
                                    notifyDataSetChanged();
                                };
                                billingClient.consumeAsync(consumeParams, listener);
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            });
            dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
            AlertDialog alertDialogLogoutAccount = dialogBuilder.create();
            alertDialogLogoutAccount.show();
        });
    }


    @Override
    public int getItemCount() {
        return skuDetailsList.size();
    }


    static class ViewHolder extends RecyclerView.ViewHolder {
        DrawerMyDonationBinding binding;

        ViewHolder(DrawerMyDonationBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }

}
