package kr.co.compcareworker.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.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

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;
import kr.co.compcareworker.Util.MyOnItemClick;

public class SearchCompanyDialog extends Dialog implements MyOnItemClick {

    Context context;
    private Handler handler, hdr;
    FragmentActivity fa;
    EditText searchText;
    RecyclerView list;
    LatelyRecyclerAdapter adapter;
    String keyword;
    boolean cp_type = true;

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

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

    @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 LatelyRecyclerAdapter(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);

                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();
                                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("cp_idx", value.getString("cp_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 + "");

        if(cp_type) {
            data.put("type", "본사");
        }
        new ApiClient(data, "proc_company_search", hdr);
    }
}
