package xn.xxp.home.setting;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.bumptech.glide.Glide;
import com.njlz.face.FaceUtils;

import java.util.List;

import http.client.HttpTool;
import xn.xxp.databinding.ItemFaceBinding;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.Face;

public class FaceAdapter extends BaseAdapter {
    private final List<String> faceIdList;

    public FaceAdapter(List<String> faceIdList) {
        this.faceIdList = faceIdList;
    }

    @Override
    public int getCount() {
        return null != faceIdList && !faceIdList.isEmpty() ? faceIdList.size() : 0;
    }

    @Override
    public String getItem(int position) {
        return null != faceIdList && !faceIdList.isEmpty() ? faceIdList.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            ItemFaceBinding binding = ItemFaceBinding.inflate(LayoutInflater.from(parent.getContext()));
            convertView = binding.getRoot();
            viewHolder = new ViewHolder(binding);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        String faceId = getItem(position);
        if (null != faceId) {
            Face face = RoomTool.getInstance().faceDao().getById(Long.parseLong(faceId));
            if (null != face) {
                Glide.with(viewHolder.binding.iv).load(HttpTool.checkUrl(face.getFaceUrl())).into(viewHolder.binding.iv);
                viewHolder.binding.name.setText(TextUtils.isEmpty(face.getUserName()) ? "" : face.getUserName());
            }
            viewHolder.binding.faceId.setText(TextUtils.isEmpty(faceId) ? "" : faceId);
        }

        return convertView;
    }

    static class ViewHolder {
        private final ItemFaceBinding binding;

        public ViewHolder(ItemFaceBinding binding) {
            this.binding = binding;
        }
    }
}
