package com.example.aymen.webservices;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

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

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

    private Contenu contenu;
    private Context context;

    public ProcessGetContenu(Context context) {
        super();

        this.context = context;
    }



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

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

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

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

            contenu = parse(json);
            Intent i = new Intent(context, ArticleActivity.class);
            i.putExtra("TITLE", contenu.getTitle());
            i.putExtra("BODY", contenu.getBody());
            i.putExtra("IMAGE", contenu.getPhotos());
            context.startActivity(i);

            // n7ébék yé safaaaa


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


    private Contenu parse(JSONArray json) throws JSONException {


        Log.e("JSON 2  : ",json.toString());

        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 body = jsonImage.getString("body");
            String descriptif = jsonImage.getString("descriptif");
            String photos = jsonImage.getString("photos");
            Contenu contenu = new Contenu(nid, title, date, link, theme, theme_tid, image, small_image, descriptif, body, photos);
            return contenu;
        }

        return new Contenu();

    }
}