package app.hima.net;

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

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

import android.os.AsyncTask;
import android.util.Log;
import app.hima.data.Message;
import app.hima.tool.Preferences;

public class HasNewMessage extends AsyncTask<Integer, Integer, List<Message>> {
	@Override
	protected List<Message> doInBackground(Integer... params) {
		String URL = ServerRequest.SERVER + "hasNewMessage.pl?id=" + Preferences.id;
		List<Message> resultat = new ArrayList<Message>();
		
		try {
			JSONArray pages = new JSONArray(ServerRequest.send(URL));

			for (int i = 0; i < pages.length(); ++i) {
				JSONObject rec = pages.getJSONObject(i);
				Log.v(this.getClass().getSimpleName(), rec.toString());
				String date = rec.getString("date");
				int user = Integer.valueOf(rec.getString("sender"));
				String message = rec.getString("message");
				int id = Integer.valueOf(rec.getString("id"));
				resultat.add(new Message(id, user, false, message, date));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return resultat;
	}
}
