package ai.pai.client.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.common.utils.TimeUtils;

import java.util.ArrayList;

import ai.pai.client.R;
import ai.pai.client.activity.GroupActivity;
import ai.pai.client.beans.GroupInfo;
import ai.pai.client.utils.GroupCreateUtils;

public class HistoryGroupAdapter extends RecyclerView.Adapter<HistoryGroupAdapter.GroupViewHolder> {

    private Context context;
    private LayoutInflater mInflater;
    private ArrayList<GroupInfo> groupList;

    public HistoryGroupAdapter(Context context, ArrayList<GroupInfo> groupList){
        this.context = context;
        this.groupList = groupList;
        mInflater = LayoutInflater.from(context);
    }


    @Override
    public GroupViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.history_group_item,parent,false);
        GroupViewHolder viewHolder = new GroupViewHolder(view);
        viewHolder.avatar = (ImageView)view.findViewById(R.id.iv_group_avatar);
        viewHolder.name = (TextView)view.findViewById(R.id.tv_group_name);
        viewHolder.time = (TextView)view.findViewById(R.id.tv_group_create_time);
        viewHolder.contentView = view;
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(GroupViewHolder holder, int position) {
        final GroupInfo info = groupList.get(position);
        holder.time.setText(TimeUtils.getFormattedTime(info.createTime));
        holder.name.setText(info.groupName);
        holder.avatar.setImageResource(GroupCreateUtils.getDrawableIdForAvatar(info.groupAvatarId));
        holder.contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, GroupActivity.class);
                intent.putExtra("group",info);
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return groupList==null ? 0 : groupList.size();
    }

    public synchronized void clearGroupList(){
        groupList.clear();
        notifyDataSetChanged();
    }

    public synchronized void addGroupList(ArrayList<GroupInfo> groupList){
        this.groupList.addAll(groupList);
        notifyDataSetChanged();
    }

    public ArrayList<GroupInfo> getGroupList(){
        return groupList;
    }

    static class GroupViewHolder extends RecyclerView.ViewHolder{

        private ImageView avatar;
        private TextView name;
        private TextView time;
        private View  contentView;

        public GroupViewHolder(View itemView) {
            super(itemView);
        }
    }
}
