package com.ar.drawing.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

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

import com.ar.drawing.listener.OnClickListener;
import com.ar.drawing.others.Utils;
import com.ar.drawing.MyDraw;
import com.ar.drawing.R;
import com.ar.drawing.customer.MyTv;

import java.util.List;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.HomeVH> {
    private List<String> nameList = MyDraw.getAllDir();

    private Context mCon;
    private String dir;

    private int count = 4;
    private OnClickListener listener;
    public MainAdapter(Context mCon) {
        this.mCon = mCon;
    }

    public void setListener(OnClickListener listener) {
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull HomeVH holder, int position) {
        String dir = nameList.get(position);
        String filePath = dir + "/1.jpg";
        Bitmap bitmap = Utils.loadImageFromAssets(mCon, filePath);
        String substring = dir.substring(dir.lastIndexOf("_") + 1);

        holder.name.setText(substring);
        holder.previewIm.setImageBitmap(bitmap);

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) holder.cardView.getLayoutParams();


        int intValue = Math.round(Utils.dpToPx(15));
        if(position == nameList.size()-1||position == nameList.size()-2){
            layoutParams.setMargins(intValue, intValue, intValue, intValue);

        }else {
            layoutParams.setMargins(intValue, intValue, intValue, 0);
        }
        holder.cardView.setLayoutParams(layoutParams);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener!= null){
                    listener.onClickItem(dir);
                }

            }
        });


    }

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

    public static class HomeVH extends RecyclerView.ViewHolder {
        private ImageView previewIm;
        private CardView cardView;
        private MyTv name;

        public HomeVH(@NonNull View itemView) {
            super(itemView);
            previewIm = itemView.findViewById(R.id.imPreview);
           cardView = itemView.findViewById(R.id.item_card);
            name = itemView.findViewById(R.id.name);
        }


    }
}
