package com.retrytech.strangerapp.adapter;

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

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

import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ItemCoinPackagesBinding;
import com.retrytech.strangerapp.modal.coinpackage.CoinPackages;
import com.retrytech.strangerapp.retrofit.Const;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CoinPackageAdapter extends RecyclerView.Adapter<CoinPackageAdapter.CoinPackageViewHolder> {

    private List<CoinPackages.Data> mList = new ArrayList<>();
    private int lastPosition = 0;

    public List<CoinPackages.Data> getmList() {
        return mList;
    }

    public void setmList(ArrayList<CoinPackages.Data> mList) {
        this.mList = mList;
    }

    public CoinPackages.Data getLastPositionData() {
        return mList.get(lastPosition);
    }

    public void setLastPosition(int lastPosition) {
        this.lastPosition = lastPosition;
    }

    @NonNull
    @Override
    public CoinPackageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_coin_packages, parent, false);
        return new CoinPackageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CoinPackageViewHolder holder, int position) {
        holder.setModal(position);
    }

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

    public void updateData(List<CoinPackages.Data> items) {
        mList = items;
        Collections.reverse(mList);
        notifyDataSetChanged();
    }

    private void changeBackground(int position) {
        notifyItemChanged(lastPosition);
        lastPosition = position;
        notifyItemChanged(position);
    }

    public class CoinPackageViewHolder extends RecyclerView.ViewHolder {
        ItemCoinPackagesBinding binding;

        public CoinPackageViewHolder(@NonNull View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);
        }

        public void setModal(int position) {
            CoinPackages.Data item = mList.get(position);

            if (lastPosition == position) {
                binding.loutSelected.setVisibility(View.VISIBLE);
            } else {
                binding.loutSelected.setVisibility(View.GONE);
            }

            binding.tvCoinPlans.setText(item.getTitle());
            binding.tvPrice.setText(Const.CURRENCY + item.getPrice());
            binding.getRoot().setOnClickListener(view -> {
                changeBackground(position);

            });


        }
    }
}
