package com.gh.gamecenter.feature.game;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.BitmapUtils;
import com.gh.gamecenter.core.provider.IPackageUtilsProvider;
import com.gh.gamecenter.feature.R;
import com.gh.gamecenter.feature.databinding.DialogSelectGameItemBinding;
import com.gh.gamecenter.feature.entity.InstallGameEntity;
import com.lightgame.adapter.BaseRecyclerAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by khy on 2017/4/1.
 */
public class SelectGameAdapter extends BaseRecyclerAdapter<SelectGameViewHolder> {

    private OnRequestCallBackListener listener;

    private List<InstallGameEntity> apkList;

    private ProgressBar pb;

    private String platformRequestsId;

    public SelectGameAdapter(AppCompatActivity activity, OnRequestCallBackListener listener, ProgressBar pb) {
        super(activity);
        this.listener = listener;
        this.pb = pb;

        apkList = new ArrayList<>();

        initData();
    }

    public SelectGameAdapter(BaseFragment fragment, ProgressBar pb) {
        super(fragment.getContext());
        this.listener = fragment;
        this.pb = pb;

        apkList = new ArrayList<>();

        initData();
    }

    public SelectGameAdapter(BaseFragment fragment, ProgressBar pb, String platformRequestsId) {
        super(fragment.getContext());
        this.listener = fragment;
        this.pb = pb;
        this.platformRequestsId = platformRequestsId;

        apkList = new ArrayList<>();

        initData();
    }

    private void initData() {
        Observable
                .create(emitter -> {
                    PackageManager pm = mContext.getPackageManager();
                    IPackageUtilsProvider packageUtilsConfig = (IPackageUtilsProvider) ARouter.getInstance().build(RouteConsts.provider.packageUtils).navigation();
                    List<PackageInfo> installedPackages = packageUtilsConfig.getInstalledPackages(mContext, 0);

                    for (PackageInfo installedPackage : installedPackages) {
                        if ((installedPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                            InstallGameEntity installGameEntity = new InstallGameEntity();
                            installGameEntity.setGamePath(installedPackage.applicationInfo.sourceDir);
                            try {
                                Drawable drawable = installedPackage.applicationInfo.loadIcon(pm);
                                installGameEntity.setGameBm(BitmapUtils.drawableToBitmap(drawable, true));

                                installGameEntity.setGameVersion(installedPackage.versionName);
                                installGameEntity.setGameName(installedPackage.applicationInfo.loadLabel(pm).toString());
                                installGameEntity.setPackageName(installedPackage.packageName);
                                installGameEntity.setVersionCode(installedPackage.versionCode);
                                if (installGameEntity.getGamePath() != null && installGameEntity.getGamePath().length() > 0) {
                                    int dot = installGameEntity.getGamePath().lastIndexOf('.');
                                    if ((dot > -1) && (dot < installGameEntity.getGamePath().length() - 1)) {
                                        installGameEntity.setFormat(installGameEntity.getGamePath().substring(dot + 1));
                                    }
                                }

                                File file = new File(installedPackage.applicationInfo.sourceDir);
                                installGameEntity.setGameSize(file.length());

                                apkList.add(installGameEntity);

                            } catch (Exception ignore) {

                            }
                        }
                    }
                    emitter.onComplete();
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<Object>() {
                    @Override
                    public void onComplete() {
                        super.onComplete();
                        notifyDataSetChanged();
                        pb.setVisibility(View.GONE);
                    }
                });
    }

    @Override
    public SelectGameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new SelectGameViewHolder(DialogSelectGameItemBinding.inflate(mLayoutInflater, parent, false));
    }

    @Override
    public void onBindViewHolder(SelectGameViewHolder holder, int position) {
        final InstallGameEntity installGameEntity = apkList.get(position);
        if (platformRequestsId != null) {
            installGameEntity.setPlatformRequestsId(platformRequestsId);
        }
        holder.binding.gameIcon.getIconIv().setImageBitmap(installGameEntity.getGameBm());
        holder.binding.gameIcon.getIconDecoratorIv().setVisibility(View.GONE);
        holder.binding.gameName.setText(installGameEntity.getGameName());
        holder.binding.gameName.setTextColor(ContextCompat.getColor(mContext, R.color.text_title));

        holder.binding.getRoot().setOnClickListener(v -> listener.loadDone(installGameEntity));
    }

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