package com.wall.wallpaper.hd.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.wall.wallpaper.hd.R;
import com.wall.wallpaper.hd.javabean.Data;
import com.wall.wallpaper.hd.listener.ItemClickListener;
import com.wall.wallpaper.hd.tools.CommonUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class AdapterList extends RecyclerView.Adapter<AdapterList.MyViewHolder> {


    private List<Data> dataInfo = new ArrayList<>();

    private ItemClickListener itemClickListener;
    private WeakReference<Context> weakReference;
    private int itemHeight;


    public void setInfoWallpaperListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public AdapterList(Context myCon, int itemHeight) {
        weakReference = new WeakReference<>(myCon);
        this.itemHeight = itemHeight;
    }

    public void setDataInfo(List<Data> dataInfo) {
        this.dataInfo = dataInfo;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = weakReference.get();
        if (context != null) {
            View itemView = LayoutInflater.from(context).inflate(R.layout.item_list, parent, false);
            ImageView imageView = itemView.findViewById(R.id.wallpaper);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            layoutParams.height = itemHeight;
            imageView.setLayoutParams(layoutParams);
            return new MyViewHolder(itemView);
        }
        return null;


    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Data info = dataInfo.get(position);
        ImageView imageView = holder.getImageView();
        String previewUrl400 = info.getPreviewUrl400();
        String previewUrl200 = info.getPreviewUrl200();
        RelativeLayout item = holder.getLayout();
        String imId = info.getImId();
        int curheight;


        MultiTransformation<Bitmap> multiTransformation = new MultiTransformation<>(
                new CenterCrop(),
                new RoundedCornersTransformation(CommonUtils.dp2Px(12), 0) // 圆角效果
        );
        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565);
        Context context = weakReference.get();
        if (context != null) {
            Glide.with(context)
                    .asDrawable()
                    .skipMemoryCache(true)
                    .apply(options)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .load(previewUrl400)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .placeholder(R.mipmap.im_placeholder)
                    .transform(multiTransformation)
                    .into(imageView);
        }

//        ImageView imFavorite = holder.getImFavorite();
//        if (idDownload) {
//            imFavorite.setVisibility(View.GONE);
//        } else {
//            imFavorite.setVisibility(View.VISIBLE);
//            boolean b = DbManager.queryIsLike(imId);
//            imFavorite.setSelected(b);
//            imFavorite.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    boolean selected = imFavorite.isSelected();
//                    imFavorite.setSelected(!selected);
//
//                    if (imFavorite.isSelected()) {
//                        DbManager.insertOrUpdateLike(info);
//                    } else {
//                        DbManager.deleteLike(info);
//                    }
//                }
//            });
//        }


        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null) {
                    itemClickListener.onItemClickAction(info);
                }

            }
        });

    }

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

    @Override
    public void onViewRecycled(@NonNull MyViewHolder holder) {
        super.onViewRecycled(holder);
//        Context context = weakReference.get();
//        if (context != null) {
//            Glide.with(context).clear(holder.getImageView());
//            Log.d(MyWallpaper.TAG, "----------onViewRecycled");
//        }

    }

    // 更新数据集
//    public void updateList(List<String> newList) {
//        // 计算差异
//        DiffUtil.Callback callback = new MyCallback(dataInfo, newList);
//        DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
//
//        // 更新数据集
//        dataInfo = mNewList;
//        mNewList = newList;
//        result.dispatchUpdatesTo(this);
//    }
    private static DiffUtil.ItemCallback<Data> diff = new DiffUtil.ItemCallback<Data>() {


        @Override
        public boolean areItemsTheSame(@NonNull Data oldItem, @NonNull Data newItem) {
            return oldItem.getImId().equals(newItem.getImId());
        }

        @Override
        public boolean areContentsTheSame(@NonNull Data oldItem, @NonNull Data newItem) {
            return oldItem.getImId().equals(newItem.getImId());
        }
    };

    private static class MyCallback extends DiffUtil.Callback {
        private List<Data> mOldList;
        private List<Data> mNewList;

        public MyCallback(List<Data> oldList, List<Data> newList) {
            mOldList = oldList;
            mNewList = newList;
        }

        @Override
        public int getOldListSize() {
            return mOldList.size();
        }

        @Override
        public int getNewListSize() {
            return mNewList.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return mOldList.get(oldItemPosition).getImId().equals(mNewList.get(newItemPosition).getImId());
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return mOldList.get(oldItemPosition).getImId().equals(mNewList.get(newItemPosition).getImId());
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView imageView;
        private RelativeLayout layout;

        //        private ImageView imFavorite;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.wallpaper);
            layout = itemView.findViewById(R.id.layout);
//            imFavorite = itemView.findViewById(R.id.image_favorite);
        }

//        public ImageView getImFavorite() {
//            return imFavorite;
//        }

        public RelativeLayout getLayout() {
            return layout;
        }

        public ImageView getImageView() {
            return imageView;
        }
    }

}
