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 android.widget.Toast;
import app.hima.data.Message;
import app.hima.tool.MessageAdapter;

public class GetMessage extends AsyncTask<Integer, Integer, List<Message>> {

	private MessageAdapter adapter;
	

	public GetMessage(MessageAdapter messageAdapter) {
		this.adapter = messageAdapter;
	}

	@Override
	protected List<Message> doInBackground(Integer... params) {
		final String URL = ServerRequest.SERVER + "get.pl?nb=15";
		List<Message> resultat = new ArrayList<Message>();
	
		try {
			JSONArray pages = new JSONArray(ServerRequest.send(URL));
			Log.v(this.getClass().getSimpleName(), pages.length() + "");
			
			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("user"));
            String message =  rec.getString("message");
            resultat.add(new Message(0, user, true,  message, date));
		}
		} catch (JSONException e) {
			e.printStackTrace();
		}
        return resultat;
	}
	
	@Override
	protected void onPostExecute(List<Message> result) {
		if(result.size()<1)
		{
			Toast.makeText(this.adapter.getContext(), "メッセージを更新できませんでした。", Toast.LENGTH_SHORT).show();
			return;
		}
		this.adapter.getMessages().clear();
		this.adapter.getMessages().addAll(result);
		this.adapter.notifyDataSetChanged();
		Toast.makeText(this.adapter.getContext(), "メッセージを更新しました。", Toast.LENGTH_SHORT).show();
    }
}
