package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

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.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class AddPlaceDialog extends Dialog {

    private Context context;
    private String ag_idx, pt_idx, map_x, map_y, cp_zip, cp_airline;
    private Handler hdr;
    private TextView dlg_company_addrTV, dlg_company_saveTV;
    private EditText dlg_company_nameET, dlg_company_addr_subET, dlg_company_running_timeET, dlg_company_running_dayET;
    private Spinner dlg_company_selectSN;
    private ArrayItem<CompanyData> companyItems;
    private ArrayAdapter<String> place_adapter;
    private int position = -1;

    public AddPlaceDialog(@NonNull Context context, Handler hdr, String ag_idx, String pt_idx, int position) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
        this.position = position;
    }

    public AddPlaceDialog(@NonNull Context context, Handler hdr, String ag_idx, String pt_idx) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.dlg_add_company);

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

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.95f);
        int y = (int) (size.y * 0.90f);

        thisWindow.setLayout(x, y);

        dlg_company_selectSN = findViewById(R.id.dlg_company_selectSN);
        dlg_company_nameET = findViewById(R.id.dlg_company_nameET);
        dlg_company_addrTV = findViewById(R.id.dlg_company_addrTV);
        dlg_company_addr_subET = findViewById(R.id.dlg_company_addr_subET);
        dlg_company_running_timeET = findViewById(R.id.dlg_company_running_timeET);
        dlg_company_running_dayET = findViewById(R.id.dlg_company_running_dayET);
        dlg_company_saveTV = findViewById(R.id.dlg_company_saveTV);

        init_Handler();
        init_Listener();

        if(position > -1) {
            Get_partner();
        }
    }

    void Set_Contents (){

        dlg_company_nameET.setText(companyItems.getArrayitem().get(position).getCpName());
        if (companyItems.getArrayitem().get(position).getCpName().equals("본사")) dlg_company_nameET.setEnabled(false);

        dlg_company_addrTV.setText(companyItems.getArrayitem().get(position).getCpAddr());
        dlg_company_addr_subET.setText(companyItems.getArrayitem().get(position).getCpAddrSub());
        dlg_company_running_timeET.setText(companyItems.getArrayitem().get(position).getCpRunningTime());
        dlg_company_running_dayET.setText(companyItems.getArrayitem().get(position).getCpRunningDay());
        if (companyItems.getArrayitem().get(position).getCpZip() != null) {
            cp_zip = companyItems.getArrayitem().get(position).getCpZip();
        }
        if (companyItems.getArrayitem().get(position).getCpMapx() != null) {
            map_x = companyItems.getArrayitem().get(position).getCpMapx();
        }
        if (companyItems.getArrayitem().get(position).getCpMapy() != null) {
            map_y = companyItems.getArrayitem().get(position).getCpMapy();
        }

    }

    void init_Listener() {

        //저장버튼 클릭 리스너
        dlg_company_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cp_name = dlg_company_nameET.getText().toString();
                String cp_addr = dlg_company_addrTV.getText().toString();
                String cp_addr_sub = dlg_company_addr_subET.getText().toString();
                String cp_running_time = dlg_company_running_timeET.getText().toString();
                String cp_running_day = dlg_company_running_dayET.getText().toString();

                if(TextUtils.isEmpty(cp_name) || TextUtils.isEmpty(cp_addr) || TextUtils.isEmpty(cp_addr_sub) || TextUtils.isEmpty(cp_running_time) || TextUtils.isEmpty(cp_running_day)){
                    Common.getInstance().toastShow(getContext(), "전체 항목을 입력해주세요.");
                    return;
                }

                if (TextUtils.isEmpty(cp_zip) || TextUtils.isEmpty(map_x) || TextUtils.isEmpty(map_y)) {
                    Common.getInstance().toastShow(getContext(), "주소가 올바르지 않습니다. 주소검색을 통해 주소를 다시 입력해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("pt_idx", pt_idx);
                data.put("cp_name", cp_name);
                data.put("cp_addr", cp_addr);
                data.put("cp_addr_sub", cp_addr_sub);
                data.put("cp_zip", cp_zip);
                data.put("cp_running_time", cp_running_time);
                data.put("cp_running_day", cp_running_day);
                data.put("cp_mapx", map_x);
                data.put("cp_mapy", map_y);
                data.put("cp_airline", "기본값");

                if (position > -1) {
                    data.put("cp_idx", companyItems.get(position).getCpIdx());

                    if (companyItems.get(position).getCpAirline() != null) {
                        data.put("cp_airline", companyItems.get(position).getCpAirline().toString());
                    }
                }

                Log.d("데이터 확인@@@@", data.toString());
                new ApiClient(data, "proc_admin_add_company", hdr);
            }
        });

        dlg_company_addrTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchAddressDialog dialog = new SearchAddressDialog(getContext(), new SearchAddressDialog.SearchAddressListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> data) {
                        cp_zip = data.get("zonecode");
                        map_x = data.get("lnt");
                        map_y = data.get("lot");
                        dlg_company_addrTV.setText(data.get("Address"));
                        dlg_company_addr_subET.setText(data.get("buildingName"));
                    }
                });
                dialog.show();
            }
        });
    }

    void Get_partner() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("pt_idx", pt_idx);
        data.put("type", "COMPANY");
        new ApiClient(data, "proc_admin_partner_view", hdr);
    }

    void init_Handler() {

        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {
                    if (url.equals("proc_admin_partner_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        companyItems = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                        }.getType());

                        if (companyItems.isSuccess()) {
                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                        }

                    } else if (url.equals("proc_admin_add_company")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if(result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")){

                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            dismiss();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            dismiss();
                        }

                    } else {
                        Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

        };
    }
}


