package org.keyscience.BackgroundTask;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.keyscience.adapters.LeaderBoardAdapter;
import org.keyscience.models.LeaderBoardModel;
import org.keyscience.network.DatabaseConnection;

import java.lang.ref.WeakReference;
import java.util.List;

public class LeaderBoardLoaderTask extends AsyncTask<String, Integer, LeaderBoardAdapter> {

    private WeakReference<RecyclerView> recyclerViewWeakReference;
    private WeakReference<Context> contextWeakReferenceReference;
    private List<LeaderBoardModel> list;

    public LeaderBoardLoaderTask(RecyclerView recyclerView, Context context, List<LeaderBoardModel> list) {
        this.list = list;
        this.recyclerViewWeakReference = new WeakReference<>(recyclerView);
        this.contextWeakReferenceReference = new WeakReference<>(context);
    }

    @Override
    protected LeaderBoardAdapter doInBackground(String... strings) {

        try {
            JSONArray jsonArray = new JSONArray(DatabaseConnection.getJSON(strings[0]));

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                LeaderBoardModel model = new LeaderBoardModel(jsonObject.getString("display_name"),
                        jsonObject.getString("user_email"), jsonObject.getInt("totalpoints"));
                list.add(model);
            }

            return new LeaderBoardAdapter(list, contextWeakReferenceReference.get());
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(LeaderBoardAdapter leaderBoardAdapter) {
        super.onPostExecute(leaderBoardAdapter);
        if (leaderBoardAdapter != null) {
            recyclerViewWeakReference.get().setAdapter(leaderBoardAdapter);
        }
    }
}
