package org.keyscience.BackgroundTask;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.keyscience.SingletonPattern.ListSingleton;
import org.keyscience.adapters.EventsAdapter;
import org.keyscience.models.EventsNewsModel;
import org.keyscience.network.DatabaseConnection;

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

public class LoadContentTask extends AsyncTask<String, Integer, EventsAdapter> {

    private WeakReference<RecyclerView> recyclerViewWeakReference;
    private WeakReference<Context> contextWeakReferenceReference;
    private WeakReference<LinearLayout> linearLayoutWeakReference;
    private WeakReference<Button> buttonWeakReference;
    private ListSingleton list;

    public LoadContentTask(RecyclerView recyclerView, Context context, ListSingleton list, LinearLayout linearLayout, Button button) {
        this.list = list;
        this.recyclerViewWeakReference = new WeakReference<>(recyclerView);
        this.contextWeakReferenceReference = new WeakReference<>(context);
        this.buttonWeakReference = new WeakReference<>(button);
        linearLayoutWeakReference = new WeakReference<>(linearLayout);
    }

    @Override
    protected EventsAdapter 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("Categories", json_data.getString("Categories"));
                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);
                if (isCancelled()) {
                    // this might happen if the user navigates to another fragment
                    list.clear();
                    results.clear();
                    break;
                }
            }

//            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++) {
            EventsNewsModel model = new EventsNewsModel();
            //build model
            model.setCategories(results.get(i).get("Categories"));
            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()) {
                // this might happen if the user navigates to another fragment
                list.clear();
                results.clear();
                break;
            }
        }
        return new EventsAdapter(list.getList(), contextWeakReferenceReference.get());
    }


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