package org.keyscience.BackgroundTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.keyscience.SingletonPattern.LabsSingletonList;
import org.keyscience.SingletonPattern.ListSingleton;
import org.keyscience.adapters.CspLearnAdapter;
import org.keyscience.models.CspLearnModel;
import org.keyscience.network.DatabaseConnection;

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

public class CspLearnAsync extends AsyncTask<String, Integer, CspLearnAdapter> {

    private WeakReference<RecyclerView> recyclerViewWeakReference;
    private WeakReference<Context> contextWeakReferenceReference;
    private WeakReference<LinearLayout> linearLayoutWeakReference;
    private LabsSingletonList list;

    public CspLearnAsync(RecyclerView recyclerView, Context context, LabsSingletonList list, LinearLayout linearLayout) {
        this.recyclerViewWeakReference = new WeakReference<>(recyclerView);
        this.contextWeakReferenceReference = new WeakReference<>(context);
        linearLayoutWeakReference = new WeakReference<>(linearLayout);
        this.list = list;

    }

    @Override
    protected CspLearnAdapter doInBackground(String... urls) {

        //********************************************************
        DatabaseConnection.callPhpPage(urls[0]);

        // url string can also be set to getNewsData.php as it also displays JSON data.
        String result = DatabaseConnection.getJSON(urls[1]);
        List<HashMap<String, String>> results = new ArrayList<>();
        JSONArray jArray;
        try {
            jArray = new JSONArray(result);

            for (int i = 0; i < jArray.length(); i++) {
                HashMap<String, String> hm = new HashMap<>();

                JSONObject json_data = jArray.getJSONObject(i);

                hm.put("guid", json_data.getString("guid"));
                hm.put("post_title", json_data.getString("post_title"));
                hm.put("post_content", json_data.getString("post_content"));
                hm.put("post_date", json_data.getString("post_date"));
                hm.put("Image", json_data.getString("Image"));

                results.add(hm);
            }

            // use HTML CDATA to add in the content using TextViews (Including images)
            for (HashMap<String, String> model : results) {
                Log.d("LINE ", String.format("Date: %s \nContent: %s\n\n", model.get("post_date"), model.get("post_content")));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //********************************************************

        // change loop to retrieve every item on JSON, use i to show progress

        for (int i = 0; i < results.size(); i++) {
            CspLearnModel model = new CspLearnModel();


            //build model
            model.setGUID(results.get(i).get("guid"));
            model.setTitle(results.get(i).get("post_title"));
            model.setDate(results.get(i).get("post_date"));
            model.setContent(results.get(i).get("post_content"));
            Bitmap image = DatabaseConnection.getBitmapFromURL(results.get(i).get("Image"));
            model.setImage(image);

            list.add(model);
            if (isCancelled()) {
                // need to free resources if task gets cancel
                // this might happen if the user navigates to another fragment
                list.clear();
                results.clear();
                break;
            }
        }


        return new CspLearnAdapter(list.getList(), contextWeakReferenceReference.get());
    }


    @Override
    protected void onPostExecute(CspLearnAdapter cspLearnAdapter) {
        super.onPostExecute(cspLearnAdapter);
        linearLayoutWeakReference.get().setVisibility(View.GONE);
        // use the weakreference to set the recyclerview adapter
        recyclerViewWeakReference.get().setAdapter(cspLearnAdapter);
    }

}
