package kr.co.compcarecompany.Util.Adapter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

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

import java.util.ArrayList;

import kr.co.compcarecompany.Data.Lately.LatelyData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.MyOnItemClick;

public class LatelyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context context;
    Handler handler;

    public int showPosition = 0;
    boolean first = false;

    // adapter에 들어갈 list 입니다.
    private ArrayList<LatelyData> items = new ArrayList<>();

    private LatelyAdapter.OnLoadMoreListener onLoadMoreListener;
    private GridLayoutManager mGridLayoutManager;
    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;
    private boolean isMoreLoading = false;
    private int visibleThreshold = 1;
    int firstVisibleItem, visibleItemCount, totalItemCount, lastVisibleItem;
    MyOnItemClick callback;

    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public LatelyAdapter(Context context, Handler handler, LatelyAdapter.OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
        this.context = context;
        this.handler = handler;
    }

    public LatelyAdapter(Context context, MyOnItemClick callback) {
        this.context = context;
        this.callback = callback;
    }

    public void setGridLayoutManager(GridLayoutManager gridLayoutManager) {
        this.mGridLayoutManager = gridLayoutManager;
    }

    public void setRecyclerView(RecyclerView mView) {
        mView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                visibleItemCount = recyclerView.getChildCount();
                totalItemCount = mGridLayoutManager.getItemCount();
                firstVisibleItem = mGridLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = mGridLayoutManager.findLastVisibleItemPosition();

//                if (!isMoreLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
//                    if (onLoadMoreListener != null) {
//                        onLoadMoreListener.onLoadMore();
//                    }
//                    isMoreLoading = true;
//                }
            }
        });
    }

    @Override
    public int getItemViewType(int position) {
        return items.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_ITEM) {
            return new LatelyAdapter.ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_lately, parent, false));
        } else {
            return new LatelyAdapter.ProgressViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_progress, parent, false));
        }
    }

    public void addAll(ArrayList<LatelyData> lst) {
        items.clear();
        items.addAll(lst);
        notifyDataSetChanged();
    }

    public void addItemMore(ArrayList<LatelyData> lst) {
        items.addAll(lst);
        notifyItemRangeChanged(0, items.size());
    }

    public void clearItem() {
        items.clear();
        notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof LatelyAdapter.ItemViewHolder) {
            LatelyData singleItem = items.get(position);
            ((LatelyAdapter.ItemViewHolder) holder).onBind(items.get(position));

        }
    }

    public void setMoreLoading(boolean isMoreLoading) {
        this.isMoreLoading = isMoreLoading;
    }

    @Override
    public int getItemCount() {
        // RecyclerView의 총 개수 입니다.
        return items.size();
    }

    public void setProgressMore(final boolean isProgress) {
        if (isProgress) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    items.add(null);
                    notifyItemInserted(items.size() - 1);
                }
            });
        } else {
            try {
                items.remove(items.size() - 1);
                notifyItemRemoved(items.size());
            } catch (Exception e) {

            }
        }
    }

    // RecyclerView의 핵심인 ViewHolder 입니다.
    // 여기서 subView를 setting 해줍니다.
    class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView name, addr, ceo;
        String cp_idx, pt_idx, pt_name, pt_code, pt_ceo, pt_condition, pt_field, pt_type, pt_gu;
        String lat, lng;

        ItemViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            addr = itemView.findViewById(R.id.addr);
            ceo = itemView.findViewById(R.id.ceo);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (callback != null) {

                        Bundle bundle = new Bundle();
                        bundle.putString("pt_idx", pt_idx);
                        bundle.putString("pt_name", pt_name);
                        bundle.putString("pt_code", pt_code);
                        bundle.putString("pt_ceo", pt_ceo);
                        bundle.putString("pt_condition", pt_condition);
                        bundle.putString("pt_field", pt_field);
                        bundle.putString("pt_type", pt_type);
                        bundle.putString("pt_gu", pt_gu);

                        callback.onClick(bundle);

                    } else {

                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("cp_idx", cp_idx);
                        bundle.putString("pt_idx", pt_idx);
                        bundle.putString("lat", lat);
                        bundle.putString("lng", lng);
                        msg.setData(bundle);
                        msg.what = 1;
                        handler.sendMessage(msg);

                    }
                }
            });
        }

        void onBind(LatelyData data) {
            name.setText(data.getPtName() + " - " + data.getCpName());
            addr.setText(data.getCpAddr());
            cp_idx = data.getCpIdx();
            pt_idx = data.getPtIdx();

            if (callback != null) {

                pt_name = data.getPtName();
                pt_code = data.getPtCode();
                pt_ceo = data.getPtCeo();
                pt_condition = data.getPtCondition();
                pt_field = data.getPtField();
                pt_type = data.getPtType();
                pt_gu = data.getPtGu();

            }

            if (!TextUtils.isEmpty(data.getPtCeo())) {

                ceo.setText(data.getPtCeo() + " 대표");
            }

            lat = data.getCpMapx();
            lng = data.getCpMapy();
        }
    }

    class ProgressViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar pBar;

        public ProgressViewHolder(View v) {
            super(v);
            pBar = v.findViewById(R.id.pBar);
        }
    }
}
