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.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ResolveInfoListAdapter extends ArrayAdapter<ResolveInfo> {
	private LayoutInflater layoutInflater = null;
	private PackageManager pm;

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

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

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

		// データ取得
		ResolveInfo resolveInfo = 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();

		// // アプリ名を取得する
		// // 取得方法によって名前が異なるようなので色々試してみる
		// ActivityInfo activityInfo = resolveInfo.activityInfo;
		// ApplicationInfo appInfo = resolveInfo.activityInfo.applicationInfo;
		// CharSequence resolveInfoLabel = resolveInfo.loadLabel(pm);
		// CharSequence activityInfoLabel = activityInfo.loadLabel(pm);
		// CharSequence appInfoLabel = appInfo.loadLabel(pm);
		// if (resolveInfoLabel.equals(activityInfoLabel)
		// && resolveInfoLabel.equals(appInfoLabel)) {
		// // とりあえず処理なし
		// } else {
		// sb.append("resolveInfo.loadLabel=" + resolveInfoLabel + "\n");
		// sb.append("activityInfo.loadLabel=" + activityInfoLabel + "\n");
		// sb.append("applicationInfo.loadLabel=" + appInfoLabel + "\n");
		// }

		// sb.append("resolveInfo="
		// + ToStringBuilder.reflectionToString(resolveInfo) + "\n");
		// sb.append("resolveInfo.activityInfo="
		// + ToStringBuilder.reflectionToString(resolveInfo.activityInfo)
		// + "\n");
		// sb.append("resolveInfo.activityInfo.applicationInfo="
		// + ToStringBuilder
		// .reflectionToString(resolveInfo.activityInfo.applicationInfo)
		// + "\n");
		// sb.append("getLaunchIntentForPackage()="
		// + pm.getLaunchIntentForPackage(resolveInfo.activityInfo.packageName)
		// + "\n");

		// 値を設定
		viewHolder.text1.setText(resolveInfo.loadLabel(pm).toString());
		viewHolder.text2.setText(sb.toString());

		return convertView;
	}
}
