package fuzion24.application.vulnerability.detector;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import fuzion24.vulnerability.checker.R;

public class VulnAppListAdapter extends BaseAdapter {
    private Activity mActivity;
    private List<ApplicationInfo> mVulnApps;
    private final PackageManager mPkgMgr;
    public VulnAppListAdapter(Activity act, List<ApplicationVulnTestResult> vulnerableApps){
      mVulnApps = vulnResultToApplicationInfoAdapter(vulnerableApps);
      mActivity = act;
      mPkgMgr = act.getPackageManager();
    }

    // I hate java.  This should be vulnerableApps.map(getApplicationInfo)
    private List<ApplicationInfo> vulnResultToApplicationInfoAdapter(List<ApplicationVulnTestResult> vulnerableApps){
        ArrayList<ApplicationInfo> list = new ArrayList<ApplicationInfo>();
        for(ApplicationVulnTestResult avtr : vulnerableApps){
            list.add(avtr.getAi());
        }

        return list;
    }

    @Override
    public int getCount() {
      return mVulnApps.size();
    }

    @Override
    public Object getItem(int position) {
      return mVulnApps.get(position);
    }

    @Override
    public long getItemId(int position) {
      return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      ApplicationInfo ai = mVulnApps.get(position);
      View view = mActivity.getLayoutInflater().inflate(R.layout.app_layout, null);
      TextView textview = (TextView) view.findViewById(R.id.android_info_text);
      ImageView imageview = (ImageView) view.findViewById(R.id.android_info_image);
      CharSequence appName = mPkgMgr.getApplicationLabel(ai);
      appName = appName == null ? ai.packageName : appName;
      textview.setText(appName);
      Drawable icon = ai.loadIcon(mPkgMgr);
      imageview.setImageDrawable(icon);
      return view;
    }

}