package kr.co.compcareworker.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.compcareworker.Data.Lately.LatelyData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.MyOnItemClick;

public class LatelyRecyclerAdapter 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 LatelyRecyclerAdapter.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 LatelyRecyclerAdapter(Context context, Handler handler, LatelyRecyclerAdapter.OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
        this.context = context;
        this.handler = handler;
    }

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

    public LatelyRecyclerAdapter(Context context, Handler handler, LatelyRecyclerAdapter.OnLoadMoreListener onLoadMoreListener, MyOnItemClick callback) {
        this.onLoadMoreListener = onLoadMoreListener;
        this.context = context;
        this.handler = handler;
        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 LatelyRecyclerAdapter.ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_lately, parent, false));
        } else {
            return new LatelyRecyclerAdapter.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 LatelyRecyclerAdapter.ItemViewHolder) {
            LatelyData singleItem = items.get(position);
            ((LatelyRecyclerAdapter.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, cp_name, cp_addr, cp_addr_sub, cp_airline;
        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);
                        bundle.putString("cp_idx", cp_idx);
                        bundle.putString("cp_name", cp_name);
                        bundle.putString("cp_addr", cp_addr);
                        bundle.putString("cp_addr_sub", cp_addr_sub);
                        bundle.putString("cp_airline", cp_airline);


                        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();
                cp_name = data.getCpName();
                cp_addr = data.getCpAddr();
                cp_addr_sub = data.getCpAddrSub();
                cp_airline = data.getCp_airline();

            }

            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);
        }
    }
}
