package org.keyscience.adapters;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
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.squareup.picasso.Picasso;

import org.keyscience.Gravatar.MD5Util;
import org.keyscience.R;
import org.keyscience.SingletonPattern.User;
import org.keyscience.models.LeaderBoardModel;
import org.keyscience.picasso.CircleTransform;

import java.util.List;

public class LeaderBoardAdapter extends RecyclerView.Adapter<LeaderBoardAdapter.LeaderBoardViewHolder> {

    private List<LeaderBoardModel> list;
    private Context context;

    public LeaderBoardAdapter(List<LeaderBoardModel> list, Context context) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public LeaderBoardViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.leaderboard_item, viewGroup, false);
        return new LeaderBoardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull LeaderBoardViewHolder leaderBoardViewHolder, int i) {
        leaderBoardViewHolder.bindData(list.get(i));
    }

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

    class LeaderBoardViewHolder extends RecyclerView.ViewHolder {

        private ImageView profileimage;
        private TextView name;
        private TextView points;

        LeaderBoardViewHolder(@NonNull View itemView) {
            super(itemView);
            profileimage = itemView.findViewById(R.id.leaderBoardUserImage);
            name = itemView.findViewById(R.id.leaderBoardName);
            points = itemView.findViewById(R.id.leaderBoardPoints);
        }

        void bindData(LeaderBoardModel model) {
            String userEmail = model.getUserEmail();
            String hash = MD5Util.md5Hex(userEmail);
            String gravatarUrl = "http://www.gravatar.com/avatar/" + hash + "?s=204&d=404";

            Picasso.get()
                    .load(gravatarUrl)
                    .transform(new CircleTransform())
                    .placeholder(R.mipmap.ic_launcher_round)
                    .resize(100, 100)
                    .centerInside()
                    .noFade()
                    .into(profileimage);

            name.setText(model.getUserName());
            points.setText(Integer.toString(model.getPoints()));

            if (User.getInstance().getEmail().equals(model.getUserEmail())) {
                // set name color to yellow if current user is the list
                name.setTextColor(Color.parseColor("#dfec98"));
            } else {
                name.setTextColor(Color.WHITE);
            }
        }
    }
}
