package com.beanpodtech.allinone.adapter;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.entity.AppInfo;

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

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

public class NativeAppAdapter extends RecyclerView.Adapter {

    private ArrayList<AppInfo> mAppInfoList;
    public NativeAppAdapter(List<AppInfo> list) {
        this.mAppInfoList = (ArrayList<AppInfo>) list;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.native_app_item, viewGroup, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }
    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, final int i) {
        ((ViewHolder) viewHolder).appIconImview.setImageDrawable(mAppInfoList.get(i).getAppIcon());
        ((ViewHolder) viewHolder).appName.setText(mAppInfoList.get(i).getAppName());
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = v.getContext().getPackageManager().getLaunchIntentForPackage(mAppInfoList.get(i).getPackageName());
                Log.d("lhs", "packagename is " + mAppInfoList.get(i).getPackageName());
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                Bundle bundle=new Bundle();
//                bundle.putCharSequence("name", mAppInfoList.get(i).getPackageName());
//                intent.putExtras(bundle);
                v.getContext().startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mAppInfoList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView appIconImview;
        TextView appName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            appIconImview = itemView.findViewById(R.id.app_icon_imageView);
            appName=itemView.findViewById(R.id.app_name_tv);

        }
    }
}
