package kr.co.compcareworker.Fragment.Search;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Lately.LatelyData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.LatelyRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

@SuppressLint("ValidFragment")
public class Search_Fragment extends Fragment implements LatelyRecyclerAdapter.OnLoadMoreListener {
    private Handler handler, hdr;

    FragmentActivity fa;

    EditText searchText;
    RecyclerView list;
    LatelyRecyclerAdapter adapter;

    int lastIndex = 0, limitCount = 10, count = 0;

    ArrayList<LatelyData> items;
    ArrayItem<LatelyData> data;

    ProgressBar progress;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @SuppressLint("ValidFragment")
    public Search_Fragment(Handler handler) {
        this.handler = handler;
    }

    public Search_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_search, container, false);
        searchText = v.findViewById(R.id.searchText);
        list = v.findViewById(R.id.list);
        progress = v.findViewById(R.id.progress);

        init_Handler();
        init_Listener();

        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 1);
        adapter = new LatelyRecyclerAdapter(getContext(), hdr, this);
        adapter.setGridLayoutManager(mLayoutManager);
        adapter.setRecyclerView(list);
        list.setAdapter(adapter);

        //Get_Contents();

        return v;
    }

    void Get_Contents() {
        progress.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("words", searchText.getText().toString());
        data.put("per_page", limitCount + "");
        data.put("offset", lastIndex + "");
        new ApiClient(data, "proc_company_search", hdr);
    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");

                    if (url != null) {
                        if (url.equals("proc_company_search")) {
                            JsonElement element = new JsonParser().parse(msg.obj.toString());
                            JsonObject result_item = element.getAsJsonObject();
                            data = new Gson().fromJson(result_item, new TypeToken<ArrayItem<LatelyData>>() {
                            }.getType());

                            items = new ArrayList<>();
                            if (data.isSuccess()) {
                                items.addAll(data.getArrayitem());
                                count = items.size();
                                if (lastIndex == 0) {
                                    adapter.addAll(items);
                                } else {
                                    adapter.addItemMore(items);
                                }

                                adapter.setMoreLoading(false);
                            } else {
                                adapter.setMoreLoading(true);
                            }

                            progress.setVisibility(View.GONE);
                        }
                    } else {
                        if (msg.getData().getString("lat") == null || msg.getData().getString("lng") == null || msg.getData().getString("lat").equals("") || msg.getData().getString("lng").equals("")) {

                            String pt_idx = msg.getData().getString("pt_idx");
                            String cp_idx = msg.getData().getString("cp_idx");

                            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                            dialogBuilder.setTitle("콤프케어 작업자");
                            dialogBuilder.setMessage("해당 업체의 좌표 데이터가 없습니다.\n장소 수정에서 정확한 주소로 수정해주세요.");
                            dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int i) {

                                    Intent intent = new Intent(getContext(), FragmentActivity.class);
                                    intent.putExtra("title", "장소정보 수정");
                                    intent.putExtra("type", "place_adjust2");
                                    intent.putExtra("value1", pt_idx);
                                    intent.putExtra("value2", cp_idx);
                                    intent.putExtra("value3", "main");
                                    startActivity(intent);
                                }
                            });
                            dialogBuilder.show();
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra("cp_idx", msg.getData().getString("cp_idx"));
                            intent.putExtra("lat", msg.getData().getString("lat"));
                            intent.putExtra("lng", msg.getData().getString("lng"));
                            getActivity().setResult(Activity.RESULT_OK, intent);
                            getActivity().finish();
                        }
                    }
                }
            }
        };
    }

    private void init_Listener() {

        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int c) {

                if (searchText.length() > 1) {
                    lastIndex = 0;
                    count = 0;
                    Get_Contents();
                } else {
                    adapter.clearItem();
                    adapter.setMoreLoading(true);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onLoadMore() {
        adapter.setProgressMore(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                adapter.setProgressMore(false);

                ///////이부분에을 자신의 프로젝트에 맞게 설정하면 됨
                //다음 페이지? 내용을 불러오는 부분
                if (count == limitCount) {
                    lastIndex += 20;
                    Get_Contents();
                }
                //////////////////////////////////////////////////
            }
        }, 500);
    }
}
