package com.ttstd.dialer.adapter;

import android.content.ComponentName;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.RecyclerView;

import com.shehuan.niv.NiceImageView;
import com.tencent.mmkv.MMKV;
import com.ttstd.dialer.R;
import com.ttstd.dialer.config.CommonConfig;
import com.ttstd.dialer.db.app.AppInfo;
import com.ttstd.dialer.fragment.dialog.shortcut.ShortcutDialogFagment;
import com.ttstd.dialer.utils.ApkUtils;
import com.ttstd.iconloader.IconCacheManager;
import com.ttstd.iconloader.IconLoader;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppHolder> implements LoaderManager.LoaderCallbacks<Drawable> {
    private static final String TAG = "AppAdapter";

    private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);

    private FragmentActivity mContext;
    private LoaderManager mLoaderManager;
    private IconCacheManager mIconCacheManager = IconCacheManager.getInstance();

    public AppAdapter(LoaderManager loaderManager) {
        mLoaderManager = loaderManager;
    }

    private List<AppInfo> mAppInfos;

    public void setAppInfos(List<AppInfo> appInfos) {
        mAppInfos = appInfos;
        notifyDataSetChanged();
    }

    public interface ShortcutCallback {
        void setAppInside(AppInfo appInfo);
    }

    private ShortcutCallback mShortcutCallback;

    public void setShortcutCallback(ShortcutCallback shortcutCallback) {
        mShortcutCallback = shortcutCallback;
    }

    @NonNull
    @NotNull
    @Override
    public AppHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        mContext = (FragmentActivity) parent.getContext();
        return new AppHolder(LayoutInflater.from(mContext).inflate(R.layout.item_app, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull AppHolder holder, int position) {
        AppInfo appInfo = mAppInfos.get(position);
        Drawable drawable = mIconCacheManager.getIcon(appInfo.getComponentName().flattenToShortString());
        if (drawable != null) {
            holder.iv_icon.setImageDrawable(drawable);
        } else {
            mLoaderManager.restartLoader(position, null, this).forceLoad();
        }
        holder.tv_app_name.setText(appInfo.getLabel());
        holder.root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApkUtils.openApp(mContext, appInfo.getComponentName());
            }
        });
        holder.root.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ShortcutDialogFagment shortcutDialogFagment = new ShortcutDialogFagment(appInfo);
                shortcutDialogFagment.setTitil("温馨提示");
                shortcutDialogFagment.setTips("是否将应用放入更多应用");
                shortcutDialogFagment.setOnClickListener(new ShortcutDialogFagment.OnClickListener() {
                    @Override
                    public void onPositiveClick() {
                        if (mShortcutCallback != null)
                            mShortcutCallback.setAppInside(appInfo);
                        shortcutDialogFagment.dismiss();
                    }

                    @Override
                    public void onNegativeClick() {
                        shortcutDialogFagment.dismiss();
                    }
                });
                shortcutDialogFagment.show(mContext.getSupportFragmentManager(), "ShortcutDialogFagment");
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mAppInfos == null ? 0 : mAppInfos.size();
    }

    @NonNull
    @NotNull
    @Override
    public Loader<Drawable> onCreateLoader(int id, @Nullable @org.jetbrains.annotations.Nullable Bundle args) {
        AppInfo appInfo = mAppInfos.get(id);
        ComponentName componentName = appInfo.getComponentName(); // 从数据项中获取 ComponentName
        return new IconLoader(mContext, componentName, mIconCacheManager);
    }

    @Override
    public void onLoadFinished(@NonNull @NotNull Loader<Drawable> loader, Drawable data) {
        int position = loader.getId();
        notifyItemChanged(position);
    }

    @Override
    public void onLoaderReset(@NonNull @NotNull Loader<Drawable> loader) {
        Log.e(TAG, "onLoaderReset: ");
    }

    public class AppHolder extends RecyclerView.ViewHolder {

        ConstraintLayout root;
        NiceImageView iv_icon;
        TextView tv_app_name;

        public AppHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            root = itemView.findViewById(R.id.root);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_app_name = itemView.findViewById(R.id.tv_app_name);
        }
    }

}
