package com.ads.cal.notes.adapter;

import android.content.Context;
import android.text.TextUtils;
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.ads.cal.notes.NoteEditActivity;
import com.ads.cal.notes.R;
import com.ads.cal.notes.bean.DataBean;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MyViewHolder> {

    private final WeakReference<Context> weakReference;
    private final ArrayList<DataBean> arrayList;

    public MainAdapter(Context context, ArrayList<DataBean> arrayList) {
        weakReference = new WeakReference<>(context);
        if (null == arrayList) {
            arrayList = new ArrayList<>();
        }
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(weakReference.get()).inflate(R.layout.item_data_layout, null, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        DataBean dataBean = arrayList.get(position);
        if (null == dataBean) {
            return;
        }
        if (!TextUtils.isEmpty(dataBean.content)) {
            holder.title.setText(dataBean.content);
        } else {
            holder.title.setText("");
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NoteEditActivity.invoke(weakReference.get(), dataBean);
            }
        });

    }

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

    public void addData(DataBean dataBean) {
        arrayList.remove(dataBean);
        arrayList.add(0, dataBean);
        notifyDataSetChanged();
    }

    public void addData(List<DataBean> list) {
        arrayList.addAll(list);
        notifyDataSetChanged();
    }

    public void deleteData(DataBean dataBean) {
        arrayList.remove(dataBean);
        notifyDataSetChanged();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        private final TextView title;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.text1);
        }
    }
}
