package co.pixelbeard.theanfieldwrap.buyTokens;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.android.billingclient.api.SkuDetails;

import java.util.List;

import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;

public class TokensAdapter extends RecyclerView.Adapter<TokensAdapter.TokensViewHolder> {

    private List<SkuDetails> mSkuDetailsList;
    private TokenPurchaseListener mListener;

    public TokensAdapter(List<SkuDetails> skuDetailsList, TokenPurchaseListener listener) {
        this.mSkuDetailsList = skuDetailsList;
        this.mListener = listener;
    }

    @NonNull
    @Override
    public TokensViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new TokensViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_in_app_purchase, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull TokensViewHolder holder, int position) {
        SkuDetails skuDetails = mSkuDetailsList.get(holder.getAdapterPosition());

        String newTitle = stripTitle(skuDetails.getTitle());

        holder.txtIapTitle.setText(newTitle);
        holder.txtIapTokenValue.setText(newTitle.replace(" tokens", ""));
        holder.txtIapDesc.setText(skuDetails.getDescription());
        holder.btnPurchase.setText(String.format(holder.itemView.getContext().getString(R.string.buy_for_arg), skuDetails.getPrice()));

        holder.btnPurchase.setOnClickListener(v -> mListener.onPurchaseSelected(skuDetails));
    }

    private String stripTitle(String title) {
        return title.replaceAll(" \\(.*\\)", "");
    }

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

    public class TokensViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.txt_iap_token_value)
        TextView txtIapTokenValue;

        @BindView(R.id.txt_iap_title)
        TextView txtIapTitle;

        @BindView(R.id.txt_iap_desc)
        TextView txtIapDesc;

        @BindView(R.id.btn_purchase)
        CircularProgressButton btnPurchase;

        public TokensViewHolder(@NonNull View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);

            txtIapTokenValue.setTypeface(FontUtils.getInstance().getDinProBlack());
            txtIapTitle.setTypeface(FontUtils.getInstance().getDinProBlack());
            txtIapDesc.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            btnPurchase.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        }
    }
}
