package com.ads.cal.picturetranslate.adapter;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.camera.core.ExperimentalGetImage;
import androidx.recyclerview.widget.RecyclerView;

import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.ThreadUtils;
import com.ads.cal.picturetranslate.Util;
import com.ads.cal.picturetranslate.activity.PictureTranslateResultActivity;
import com.ads.cal.picturetranslate.bean.PictureTranslateBean;
import com.bumptech.glide.Glide;

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

@ExperimentalGetImage
public class PictureTranslateListAdapter extends RecyclerView.Adapter<PictureTranslateListAdapter.MyViewHolder> {

    private WeakReference<Context> weakReference;
    private ArrayList<PictureTranslateBean> data;

    public PictureTranslateListAdapter(Context context, ArrayList<PictureTranslateBean> data) {
        if (weakReference == null) {
            weakReference = new WeakReference<>(context);
        }
        this.data = data;
    }

    public void updateData(PictureTranslateBean bean) {
        if (data == null) {
            data = new ArrayList<>();
        } else {
            for (PictureTranslateBean translateBean : data) {
                if (translateBean.getTime() == bean.getTime()) {
                    data.remove(translateBean);
                    break;
                }
            }
            bean.setTime(bean.getNewTime());
            data.add(0, bean);
        }
        notifyDataSetChanged();
    }

    public void updateData(List<PictureTranslateBean> beans) {
        if (data == null) {
            data = new ArrayList<>();
        } else {
            data.addAll(beans);
        }
        notifyDataSetChanged();
    }

    public boolean isDataEmpty() {
        return null == data || data.isEmpty();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(weakReference.get()).inflate(R.layout.picture_translate_list_item, null, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        PictureTranslateBean bean = data.get(position);
        holder.itemView.setOnLongClickListener(v -> {
            showPopupWindow(v, bean);
            return true;
        });
        holder.itemView.setOnClickListener(v -> PictureTranslateResultActivity.startPictureTranslateResultActivity(weakReference.get(), bean));
        if (bean == null) {
            return;
        }
        holder.setImage(weakReference.get(), bean.getImageUrl());
        holder.setTitle(bean.getTitle());
        holder.setTime(bean.getTime());
    }

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

    private void showPopupWindow(View anchorView, PictureTranslateBean bean) {

        // 获取 item 在屏幕上的坐标
        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);
        // 设置 PopupWindow 的位置
        int xOffset = 0;
        int yOffset = 0;
        int height = Util.getScreenHeight(weakReference.get());
        View contentView = null;
        TextView delete = null;
        if (location[1] > height / 2) {
            contentView = LayoutInflater.from(weakReference.get()).inflate(R.layout.delete_popuwindo_bottom_layout, null, false);
            xOffset = anchorView.getWidth() / 2; // X 偏移
            yOffset = location[1]; // Y 偏移
            delete = contentView.findViewById(R.id.delete);
        } else {
            contentView = LayoutInflater.from(weakReference.get()).inflate(R.layout.delete_popuwindo_top_layout, null, false);
            xOffset = anchorView.getWidth() / 2; // X 偏移
            yOffset = location[1] + anchorView.getHeight() / 2; // Y 偏移
            delete = contentView.findViewById(R.id.delete);
        }
        PopupWindow popupWindow = new PopupWindow(weakReference.get());
        popupWindow.setContentView(contentView);

        // 设置PopupWindow的背景为透明
        popupWindow.setBackgroundDrawable(weakReference.get().getResources().getDrawable(android.R.color.transparent));

        // 设置PopupWindow可以获取焦点，这样可以响应触摸事件
        popupWindow.setFocusable(true);

        popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY, xOffset, yOffset);
        delete.setOnClickListener(v -> {
            // 处理删除按钮点击事件，删除对应的 item
            deleteItem(bean);
            popupWindow.dismiss();
        });
    }

    private void deleteItem(PictureTranslateBean bean) {
        int position = data.indexOf(bean);
        // 从数据集中移除对应的 item 数据
        data.remove(bean);

        // 通知 RecyclerView 刷新数据
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, getItemCount());
        ThreadUtils.startRunnable(() -> PictureApplication.getDataBaseManager().deleteData(bean.getTime()));
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private final ImageView imageView;
        private final TextView mTitle;
        private final TextView time;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.item_img);
            mTitle = itemView.findViewById(R.id.item_title);
            time = itemView.findViewById(R.id.item_time);
        }

        public void setImage(Context context, String imageUrl) {
            // 使用Glide加载图片
            Glide.with(context)
                    .load(imageUrl)
                    .into(imageView);
        }

        public void setTitle(String title) {
            mTitle.setText(title);
        }

        public void setTime(long createTime) {
            time.setText(Util.getDataTime(createTime));
        }
    }
}
