package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ProgressBar;

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.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Lately.LatelyData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.LatelyAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.MyOnItemClick;

public class SearchCompanyDialog extends Dialog implements MyOnItemClick {

    Context context;
    private Handler handler, hdr;
    FragmentActivity fa;
    EditText searchText;
    RecyclerView list;
    LatelyAdapter adapter;
    String keyword;

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

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

    ProgressBar progress;

    private SearchCompanyDialog.SearchCompanyDialogListener searchCompanyDialogListener;

    public interface SearchCompanyDialogListener {
        void clickBtn(HashMap<String, String> data);
    }

    public SearchCompanyDialog(Context context, String keyword, SearchCompanyDialog.SearchCompanyDialogListener searchCompanyDialogListener) {
        super(context);
        this.context = context;
        this.searchCompanyDialogListener = searchCompanyDialogListener;
        this.keyword = keyword;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.frag_search);

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.9f);
        int y = (int) (size.y * 0.9f);

        thisWindow.setLayout(x, y);

        searchText = findViewById(R.id.searchText);
        list = findViewById(R.id.list);
        progress = findViewById(R.id.progress);

        init_Handler();
        init_Listener();

        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 1);
        adapter = new LatelyAdapter(getContext(), this::onClick);
        adapter.setGridLayoutManager(mLayoutManager);
        adapter.setRecyclerView(list);
        list.setAdapter(adapter);

    }

    void init_Handler() {

        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                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();
                            adapter.addAll(data.getArrayitem());

                        }
                        progress.setVisibility(View.GONE);

                    }
                }
            }
        };

    }

    void init_Listener() {

        if (!TextUtils.isEmpty(keyword)) {

            Get_Contents();
            keyword = null;
        }

        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.getText().length() > 1) {

                    lastIndex = 0;
                    count = 0;
                    Get_Contents();

                } else {

                    adapter.clearItem();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    @Override
    public void onClick(Bundle value) {

        HashMap<String, String> data = new HashMap();
        data.put("pt_idx", value.getString("pt_idx"));
        data.put("pt_name", value.getString("pt_name"));
        data.put("pt_code", value.getString("pt_code"));
        data.put("pt_ceo", value.getString("pt_ceo"));
        data.put("pt_condition", value.getString("pt_condition"));
        data.put("pt_field", value.getString("pt_field"));
        data.put("pt_type", value.getString("pt_type"));
        data.put("pt_gu", value.getString("pt_gu"));

        searchCompanyDialogListener.clickBtn(data);
        dismiss();
    }

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