package com.example.sleep;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

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

    private List<ItemModel> dataList; // 数据列表
    private Context context; // 上下文对象

    public MyAdapter(Context context, List<ItemModel> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    public void setDataList(List<ItemModel> dataList) {
        this.dataList = dataList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        ItemModel item = dataList.get(position);
        holder.textView.setText("用户评论: " + item.getText());

        // 尝试从文件中加载图片，如果失败则从Base64字符串解码为Bitmap
        Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeFile(item.getImageResId());
        } catch (Exception e) {
            bitmap = base64ToBitmap(item.getImageResId());
        }

        if (bitmap == null) {
            bitmap = base64ToBitmap(item.getImageResId());
        }

        holder.imageView.setImageBitmap(bitmap);
    }

    public Bitmap base64ToBitmap(String base64Encoded) {
        byte[] decodedByte = Base64.decode(base64Encoded, 0);
        return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
    }

    @Override
    public int getItemCount() {
        if (dataList == null) {
            return 0;
        }
        return dataList.size();
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;

        MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            textView = itemView.findViewById(R.id.textView);
        }
    }
}
