package com.usai.apex;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import com.usai.apex.ResultActivity.SearchTask;
import com.usai.util.Network;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class AnnouncementActivity extends ListActivity
{
	String				lastid			= "";
	int					limit			= 10;
	private SearchTask	m_task			= null;
	SearchResult		searchresult	= new SearchResult();
	BaseAdapter			adapter			= null;
	View				view_page_footer;

	String				module_name		= "";

	public void requestdata()
	{

		if (m_task != null)
		{
			return;
		}
		// mStatusMessageView.setText(R.string.str_Loading);
		// showProgress(true);
		m_task = new SearchTask();

		TextView text_page = (TextView) view_page_footer
				.findViewById(R.id.text_page);
		text_page.setText("Loading...");
		text_page.setEnabled(false);
		m_task.execute();

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);

		// Log.i("FragmentList", "Item clicked: " + id);
		Intent intent = new Intent();
		intent.putExtra("url", searchresult.getData().get(position).get("url")
				.toString());
		intent.putExtra("title", searchresult.getData().get(position).get("title")
				.toString());
		intent.setClass(this, WebActivity.class);
		startActivity(intent);
	}

	@Override
	public void onDestroy()
	{
		if (m_task != null)
			m_task.cancel(false);
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		// setTitle("Booking Result");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_announcements);
		adapter = new AnnouncementAdapter(searchresult, this);

		module_name = getIntent().getStringExtra("module_name");

		setTitle(module_name);
		view_page_footer = LayoutInflater.from(this).inflate(
				R.layout.view_page_footer, null);
		getListView().addFooterView(view_page_footer);// 添加底部视图
		TextView text_page = (TextView) view_page_footer
				.findViewById(R.id.text_page);
		text_page.setOnClickListener(new View.OnClickListener()
		{
			// 点击按钮 追加数据 并通知适配器
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				// TextView tv = (TextView) v;
				// tv.setText("Loading...");
				requestdata();
				// tv.setText("下一页");
				// adapter.notifyDataSetChanged();
			}
		});

		setListAdapter(adapter);
		// this.getListView().setBackgroundColor(Color.WHITE);
		requestdata();

	}

	class SearchTask extends AsyncTask<Void, Void, Boolean>
	{
		int		errorcode;
		boolean	bfinish	= false;

		@Override
		protected Boolean doInBackground(Void... params)
		{
			Log.d("SearchTask", "doInBackground");
			if (!Network.NetworkIsAvailable())

			{
				errorcode = Network.RESULT_NET_NOTAVAILABLE;
				return false;
			}
			String jstr;
			if (module_name.equals("Announcements"))
				jstr = Network.get_announcements(lastid, limit);
			else
				jstr = Network.get_marketnews(lastid, limit);
			if (jstr == null || jstr.length() <= 0)
			{
				// Log.d(TAG, "json is wrong");

				errorcode = Network.RESULT_NET_ERROR;
				return false;
			}

			JSONObject jsobj;
			//
			// array = new JSONArray(json);
			try
			{
				jsobj = new JSONObject(jstr);
				// if (searchresult.get_fieldscount() == 0)
				// {
				// JSONObject objfields = jsobj.getJSONObject("fields");
				// if (objfields != null)
				// searchresult.init_fields(objfields.toString());
				// }
				int count = jsobj.getInt("total");
				if (count < limit)
					bfinish = true;
				JSONObject objrecords = jsobj.getJSONObject("records");
				if (objrecords != null)
					searchresult.add_records(objrecords.toString(), count);
				errorcode = Network.RESULT_TRUE;

				return true;

			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			errorcode = Network.RESULT_NET_ERROR;
			return false;
		}

		@Override
		protected void onPostExecute(Boolean success)
		{
			String tag = "onPostExecute@AnnouncementActivity";
			Log.d("onPostExecute", "entry");
			m_task = null;
			// showProgress(false);

			switch (errorcode)
			{
				case Network.RESULT_NET_NOTAVAILABLE:
				{
					Toast toast = Toast.makeText(
							ApexTrackingApplication.get_instance(),
							getText(R.string.msg_connection_none),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}
				case Network.RESULT_NET_ERROR:
				{
					Toast toast = Toast.makeText(
							ApexTrackingApplication.get_instance(),
							getText(R.string.msg_net_error), Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}
				case Network.RESULT_ERROR:
				// case Network.RESULT_RESPONSE_NULL:
				{
					Toast toast = Toast.makeText(
							ApexTrackingApplication.get_instance(),
							getText(R.string.msg_net_resulterror),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}

				default:
					break;
			}

			if (success)
			{

				if (bfinish)
				{
					// getListView().removeFooterView(view_page_footer);
					// Toast.makeText(AnnouncementActivity.this, "Load all!",
					// Toast.LENGTH_LONG).show();

					TextView tv = (TextView) view_page_footer
							.findViewById(R.id.text_page);
					tv.setText("No more items");
					tv.setEnabled(false);
				}
				else
				{
					TextView tv = (TextView) view_page_footer
							.findViewById(R.id.text_page);
					tv.setText("More...");
					tv.setEnabled(true);
				}
				adapter.notifyDataSetChanged();
				// getListAdapter().notifyDataSetChanged;
				// BaseAdapter mJson = null;
				// mJson.notifyDataSetChanged();
			}
			else
			{
				TextView tv = (TextView) view_page_footer
						.findViewById(R.id.text_page);
				tv.setText("More...");
				tv.setEnabled(true);
			}
			super.onPostExecute(success);
		}

		@Override
		protected void onCancelled()
		{
			m_task = null;
			// showProgress(false);
		}
	}

	private class SearchResult
	{
		List<Map<String, Object>>	datalist	= new ArrayList<Map<String, Object>>();

		public int get_count()
		{
			return datalist.size();
		}

		public void add_records(String source, int count)
		{
			JSONObject objrecords;
			try
			{
				objrecords = new JSONObject(source);

				for (int i = 0; i < count; i++)
				{
					// offset++;
					JSONObject objrec = objrecords.getJSONObject("record" + i);
					String title = objrec.getString("title");
					String content = objrec.getString("content");
					String image = objrec.getString("image");
					String id = objrec.getString("id");
					String url = objrec.getString("url");
					lastid = id;
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("title", title);
					map.put("content", content);
					map.put("image", image);
					map.put("id", id);
					map.put("url", url);
					datalist.add(map);

					// Iterator<?> it = rec.keys();
					// HashMap<String, String> record = new HashMap<String,
					// String>();
					// while (it.hasNext()) // loop for each function
					// {
					// String field_name = (String) it.next();
					// String val = rec.getString(field_name)
					// .replace("\n", "");
					// record.put(field_name, val);
					// }
					// records.add(record);

				}
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		public List<Map<String, Object>> getData()
		{

			return datalist;
		}
	}

	private class AnnouncementAdapter extends BaseAdapter
	{
		private LayoutInflater	mInflater;	// 动态布局映射
		private SearchResult	result;

		// private Context context;
		// private int i = 0;
		public AnnouncementAdapter(SearchResult result, Context context)
		{
			this.result = result;
			// this.context = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return result.get_count();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			convertView = mInflater.inflate(R.layout.announcement_item, null);// 根据布局文件实例化view

			TextView title = (TextView) convertView.findViewById(R.id.tv_title);// 找某个控件
			title.setText(result.getData().get(position).get("title")
					.toString());// 给该控件设置数据(数据从集合类中来)
			TextView content = (TextView) convertView
					.findViewById(R.id.tv_content);
			content.setText(result.getData().get(position).get("content")
					.toString());
			if (result.getData().get(position).get("image").toString().length() > 0)
			{
				byte[] gzipBuff = Base64.decode(result.getData().get(position)
						.get("image").toString(), 0);

				ByteArrayInputStream memstream = new ByteArrayInputStream(
						gzipBuff, 0, gzipBuff.length);

				ByteArrayOutputStream baos = new ByteArrayOutputStream(
						gzipBuff.length);
				ImageView iv_thumb = (ImageView) convertView
						.findViewById(R.id.iv_thumb);
				try
				{
					baos.write(gzipBuff);

					Bitmap bmp = BitmapFactory.decodeStream(memstream);

					// ImageView image = new ImageView(this);

					iv_thumb.setImageBitmap(bmp);
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// img.setBackgroundResource((Integer)jObject.get("img"));

			return convertView;
		}
	}
}
