package com.example.aymen.webservices;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Async Task to get and send data to through JSON respone.
 **/
public class ProcessGetArticles extends AsyncTask<String, String, JSONArray> {

    private List<Article> articles;
    private Context context;
    private static String DISPLAY_ID;

    public ProcessGetArticles(Context context) {
        super();

        this.context = context;
    }



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected JSONArray doInBackground(String... args) {
        UserFunctions userFunction = new UserFunctions();
        DISPLAY_ID = args[0];
        JSONArray json = userFunction.getArticles(args[0], args[1]);
        return json;
    }

    @Override
    protected void onPostExecute(JSONArray json) {
        try {

//            Log.d("JSON OBJ", json.toString());

            articles = parse(json);
            System.out.println(articles);


            ListView list= (ListView) ((Activity)context).findViewById(R.id.list);

            // Create custom adapter for listview
            LazyImageLoadAdapter adapter=new LazyImageLoadAdapter(context, articles);

            //Set adapter to listview
            list.setAdapter(adapter);


            // HOUNI t3ammér el list view mté3ék :v nhébék <3
            // tsajél fl SQLite houni zéda


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


    private List<Article> parse(JSONArray json) throws JSONException {


        ArrayList<Article> records = new ArrayList<Article>();



         for(int i =0; i < json.length(); i++) {

             JSONObject jsonImage = json.getJSONObject(i);
             String nid= jsonImage.getString("nid");
             String title = jsonImage.getString("title");
             String date = jsonImage.getString("date");
             String link = jsonImage.getString("link");
             String theme = jsonImage.getString("theme");
             String theme_tid = jsonImage.getString("theme_tid");
             String image = jsonImage.getString("image");
             String small_image = jsonImage.getString("small_image");
             String descriptif = jsonImage.getString("descriptif");
             String photos = jsonImage.getString("photos");
             Article record = new Article(nid, title, date, link, theme, theme_tid, image, small_image, descriptif, photos, DISPLAY_ID);

             records.add(record);
            }

        return records;
    }
}