package org.deke.risk.riskahead.adapter;

import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.google.firebase.crashlytics.FirebaseCrashlytics;

import org.deke.risk.riskahead.R;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 *
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 *
 */
public class Top10ListAdapter extends BaseAdapter {
    private final static String TAG = Top10ListAdapter.class.getSimpleName();

    private Context context;
    private List<JSONObject> data;

    private static LayoutInflater inflater = null;

    public Top10ListAdapter(Context context, List<JSONObject> data) {
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (vi == null) vi = inflater.inflate(R.layout.fragment_top10list_row, parent, false);

        TextView rank = vi.findViewById(R.id.txt_top10_rank);
        TextView name = vi.findViewById(R.id.txt_top10_name);
        TextView numberOfIncidents = vi.findViewById(R.id.txt_top10_numberOfIncidents);
        TextView memberSince = vi.findViewById(R.id.txt_top10_membersince);
        TextView points = vi.findViewById(R.id.txt_top10_points);

        try {
            rank.setText(String.format("#%s",
                    data.get(position).getString("rank")));

            name.setText(data.get(position).getString("username"));
            name.setTypeface(null, Typeface.BOLD);
            points.setText(data.get(position).getString("points"));

            numberOfIncidents.setText(String.format("%s %s",
                    data.get(position).getString("numberOfPosts"),
                    context.getResources().getString(R.string.txt_top10_reportedinc)));

            memberSince.setText(String.format("%s %s",
                    context.getResources().getString(R.string.txt_top10_membersince),
                    data.get(position).getString("created_at").split(" ")[0]));
        } catch (JSONException e) {
            FirebaseCrashlytics.getInstance().log("JSONException caught: " + e);
            FirebaseCrashlytics.getInstance().recordException(e);
        }
        return vi;
    }
}