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.Preferences;
import app.hima.tool.UserMessageAdapter;

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

	private UserMessageAdapter adapter;

	public GetUserMessage(UserMessageAdapter userMessageAdapter) {
		this.adapter = userMessageAdapter;
	}

	@Override
	protected List<Message> doInBackground(Integer... params) {
		String URL;
		
		
		Log.v(this.getClass().getSimpleName(), "Params : " + params.length);
		if (params[0] == null) {
			URL = ServerRequest.SERVER + "getUserMessage.pl?id="
					+ Preferences.id;
		} else {
			int coid = params[0];
			URL = ServerRequest.SERVER + "getUserMessage.pl?id=" + Preferences.id + "&coid=" + coid;
			
		}
		List<Message> resultat = new ArrayList<Message>();
		
		Log.v(this.getClass().getSimpleName(), "URL : " + URL);
		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("sender"));
				String message = rec.getString("message");
				boolean read = rec.getString("read").equalsIgnoreCase("1") ? true : false;
				int id = Integer.valueOf(rec.getString("id"));
				resultat.add(new Message(id, user, read,  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();
	}
}
