package com.tryandroid.etc;

import java.util.List;

import org.apache.commons.lang.builder.ToStringBuilder;

import com.kurukurupapa.tryandroid.fw.util.LogUtil;

import android.R;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class RunningTaskInfoListAdapter extends ArrayAdapter<RunningTaskInfo> {
	private LayoutInflater layoutInflater = null;
	private PackageManager pm;

	private class ViewHolder {
		public TextView text1;
		public TextView text2;
	}

	public RunningTaskInfoListAdapter(Context context,
			List<RunningTaskInfo> list) {
		super(context, 0, list);
		this.layoutInflater = LayoutInflater.from(context);
		pm = context.getPackageManager();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LogUtil.called();

		// データ取得
		RunningTaskInfo taskInfo = getItem(position);

		// View取得
		ViewHolder viewHolder;
		if (convertView == null) {
			// View生成
			convertView = layoutInflater.inflate(R.layout.simple_list_item_2,
					null);
			viewHolder = new ViewHolder();
			viewHolder.text1 = (TextView) convertView.findViewById(R.id.text1);
			viewHolder.text2 = (TextView) convertView.findViewById(R.id.text2);
			convertView.setTag(viewHolder);
		} else {
			// Viewを使い回す
			viewHolder = (ViewHolder) convertView.getTag();
		}

		// タスク情報取得
		StringBuilder sb = new StringBuilder();
		sb.append("taskInfo=" + ToStringBuilder.reflectionToString(taskInfo)
				+ "\n");
		sb.append("getLaunchIntentForPackage()="
				+ pm.getLaunchIntentForPackage(taskInfo.topActivity
						.getPackageName()) + "\n");

		// 値を設定
		viewHolder.text1.setText(taskInfo.topActivity.getClassName());
		viewHolder.text2.setText(sb.toString());

		return convertView;
	}
}
