package kr.co.compcareworker.Util.CustomView;

import android.app.AlertDialog;
import android.app.Dialog;
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.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
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.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.Machine.Product.ProductData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ProductSearchRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.MyProductClick;

public class ProductSearchDialog extends Dialog implements MyProductClick {

    Context context;
    ProductSearchRecyclerAdapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayItem<ProductData> item_array;
    ProductData item_data;
    Handler hdr;
    RecyclerView product_searchRV;
    EditText product_nameET;
    Button searchBtn;
    ProgressBar product_progress;
    String type, ag_idx;
    InputMethodManager input;

    private ProductSearchDialogListener productSearchDialogListener;

    public ProductSearchDialog(Context context, ProductSearchDialogListener productSearchDialogListener, String ag_idx) {
        super(context);
        this.context = context;
        this.productSearchDialogListener = productSearchDialogListener;
        this.ag_idx = ag_idx;
    }

    public ProductSearchDialog(Context context, String type, String ag_idx) {
        super(context);
        this.context = context;
        this.type = type;
        this.ag_idx = ag_idx;
    }

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

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

        Window win = getWindow();
        assert win != null;
        WindowManager.LayoutParams winLp = win.getAttributes();
        winLp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
        win.setAttributes(winLp);

        product_progress = findViewById(R.id.product_progress);
        searchBtn = findViewById(R.id.searchBtn);
        product_searchRV = findViewById(R.id.product_searchRV);
        product_nameET = findViewById(R.id.search_nameET);
        adapter = new ProductSearchRecyclerAdapter(getContext(), hdr, this::myProductClick);

        input = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

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

                product_progress.setVisibility(View.VISIBLE);
                product_progress.bringToFront();

                input.hideSoftInputFromWindow(searchBtn.getWindowToken(), 0);

                Get_Product();

                product_nameET.clearFocus();
                product_nameET.getText().clear();
            }
        });

        product_nameET.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 (product_nameET.length() > 1) {
                    Get_Product();
                }

                if (product_nameET.length() < 1) {
                    adapter.clearItem();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (product_nameET.length() < 1) {
                    adapter.clearItem();
                }
            }
        });

        init_Handler();

        if (TextUtils.isEmpty(type)) {

            Get_Product();

        }

        input.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    @Override
    protected void onStop() {
        super.onStop();
        input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        dismiss();
        return true;
    }

    @Override
    public void myProductClick(ProductData pd_data) {

        HashMap<String, String> data = new HashMap();
        data.put("ag_idx", ag_idx);
        data.put("pd_idx", pd_data.getPdIdx());
        data.put("pd_code", pd_data.getPdCode());
        data.put("pd_ttype", pd_data.getPdTtype());
        data.put("pd_name", pd_data.getPdShortName());
        data.put("pd_option", pd_data.getPdSpec());

        if (!TextUtils.isEmpty(type)) {

            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
            dialogBuilder.setTitle("콤프케어 작업자");
            dialogBuilder.setMessage("선택한 제품의 코드관리를 하시겠습니까?");
            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", "code_management");
                    intent.putExtra("value1", pd_data);
                    context.startActivity(intent);

                    dialog.dismiss();
                    dismiss();
                }

            }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {

                    adapter.clearFocus();
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();

        } else {

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

    void Set_Content() {

        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        adapter = new ProductSearchRecyclerAdapter(getContext(), hdr, this::myProductClick);
        product_searchRV.setLayoutManager(layoutManager);
        adapter.addItem(item_array.getArrayitem());
        product_searchRV.setAdapter(adapter);

        product_progress.setVisibility(View.GONE);
    }

    void Get_Product() {

        product_progress.setVisibility(View.VISIBLE);
        product_progress.bringToFront();
        HashMap<String, String> data = new HashMap<>();
        data.put("pd_name", product_nameET.getText().toString());
        data.put("ag_idx", ag_idx);
        if (!TextUtils.isEmpty(type)) data.put("type", type);

        new ApiClient(data, "proc_product_view", 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.equals("proc_product_view")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        item_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ProductData>>() {
                        }.getType());

                        if (item_array.isSuccess()) {
                            if (item_array.size() > 0) {

                                for (int i = 0; i < item_array.size(); i++) {
                                    item_data = item_array.getArrayitem().get(i);
                                }
                            }
                            Set_Content();

                        } else {
                            Toast.makeText(getContext(), item_array.getMessage(), Toast.LENGTH_SHORT).show();
                            dismiss();
                        }
                    }
                }
            }
        };
    }
}
