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.util.ArraySet;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class AirLineModifyDialog extends Dialog {

    Context context;
    private String ag_idx, cp_idx, old_airline, new_airline;
    private Handler hdr;
    private Spinner dlg_air_line_selectSN;
    private TextView dlg_air_line_saveTV;
    private EditText dlg_air_line_nameET;
    private String[] air_line_array;
    private ArrayAdapter<String> air_line_adapter;
    private RadioGroup dlg_airline_modify_typeRG;
    private LinearLayout dlg_airline_deleteLL, dlg_airline_modifyLL, select_airlineLL;
    private boolean is_modify = false;
    private boolean is_delete = false;
    private ProgressBar airline_modifyPB;

    private AirLineModifyDialog.clickListener clickListener;

    public interface clickListener {
        void clickBtn();
    }

    public AirLineModifyDialog(@NonNull Context context, Handler hdr, String ag_idx, String cp_idx, String[] air_line_array, AirLineModifyDialog.clickListener clickListener) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.cp_idx = cp_idx;
        this.air_line_array = air_line_array;
        this.clickListener = clickListener;
    }

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

        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_airline_modify_typeRG = findViewById(R.id.dlg_airline_modify_typeRG);
        dlg_air_line_selectSN = findViewById(R.id.dlg_air_line_selectSN);
        dlg_air_line_nameET = findViewById(R.id.dlg_air_line_nameET);
        dlg_air_line_saveTV = findViewById(R.id.dlg_air_line_saveTV);
        dlg_airline_deleteLL = findViewById(R.id.dlg_airline_deleteLL);
        dlg_airline_modifyLL = findViewById(R.id.dlg_airline_modifyLL);
        select_airlineLL = findViewById(R.id.select_airlineLL);
        airline_modifyPB = findViewById(R.id.airline_modifyPB);

        //에어라인 스피너 초기화
        air_line_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

        if (air_line_array != null && air_line_array.length > 0) {
            air_line_adapter.add("추가");
            for (String s : air_line_array) {
                if (!s.equals("임시 에어라인"))
                    air_line_adapter.add(s);
            }
        } else {
            air_line_adapter.add("기본값");
        }

        dlg_air_line_selectSN.setAdapter(air_line_adapter);

        init_Handler();
        init_Listener();
    }

    void init_Listener() {

        dlg_airline_modify_typeRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                RadioButton button = findViewById(checkedId);
                String select = button.getText().toString();
                dlg_air_line_nameET.getText().clear();
                dlg_air_line_nameET.clearFocus();

                switch (select) {
                    case "추가":
                        is_modify = false;
                        is_delete = false;
                        old_airline = "";
                        air_line_adapter.clear();
                        air_line_adapter.add("추가");
                        air_line_adapter.addAll(air_line_array);
                        air_line_adapter.remove("임시 에어라인");
                        dlg_air_line_selectSN.setSelection(0);
                        dlg_airline_deleteLL.setVisibility(View.GONE);
                        dlg_airline_modifyLL.setVisibility(View.VISIBLE);
                        dlg_air_line_nameET.setEnabled(true);
                        break;

                    case "수정":
                        is_modify = true;
                        is_delete = false;
                        old_airline = "";
                        air_line_adapter.clear();
                        air_line_adapter.addAll(air_line_array);
                        air_line_adapter.remove("임시 에어라인");
                        dlg_airline_deleteLL.setVisibility(View.GONE);
                        dlg_airline_modifyLL.setVisibility(View.VISIBLE);
                        if (dlg_air_line_selectSN.getSelectedItem() == null) air_line_adapter.add("에어라인 없음");
                        dlg_air_line_selectSN.setSelection(0);
                        dlg_air_line_nameET.setEnabled(true);
                        break;

                    case "삭제":
                        is_modify = false;
                        is_delete = true;
                        old_airline = "";
                        air_line_adapter.clear();
                        air_line_adapter.addAll(air_line_array);
                        air_line_adapter.remove("임시 에어라인");
                        dlg_airline_deleteLL.setVisibility(View.VISIBLE);
                        if (dlg_air_line_selectSN.getSelectedItem() == null) air_line_adapter.add("에어라인 없음");
                        dlg_air_line_selectSN.setSelection(0);
                        dlg_air_line_nameET.setEnabled(false);
                        break;
                }
            }
        });

        //선택한 Air_Line
        dlg_air_line_selectSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String line = dlg_air_line_selectSN.getSelectedItem().toString();
                if (!line.equals("추가")) dlg_air_line_nameET.setText(line);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                String line = dlg_air_line_selectSN.getSelectedItem().toString();
                if (!line.equals("추가") && !line.equals("에어라인 없음")) dlg_air_line_nameET.setText(line);
            }
        });

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

                if (is_modify && dlg_air_line_selectSN.getSelectedItem().toString().equals("에어라인 없음")) {
                    Common.getInstance().toastShow(getContext(), "수정할 에어라인이 없습니다.");
                    return;
                }

                if (is_delete && dlg_air_line_selectSN.getSelectedItem().toString().equals("에어라인 없음")) {
                    Common.getInstance().toastShow(getContext(), "삭제할 에어라인이 없습니다.");
                    return;
                }

                if (!is_delete && dlg_air_line_nameET.getText().toString().equals("")) {
                    Common.getInstance().toastShow(getContext(), "에어라인명을 입력하세요.");
                    return;
                }

                String cp_airline = "";

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("cp_idx", cp_idx);

                ArrayList<String> line_list = new ArrayList(Arrays.asList(air_line_array));

                String mc_airline = dlg_air_line_nameET.getText().toString();
                String old_airline = dlg_air_line_selectSN.getSelectedItem().toString();

                if (is_modify && line_list.size() > 0) {
                    line_list.remove(old_airline);
                    line_list.add(mc_airline);
                    data.put("mc_airline", mc_airline);
                    data.put("old_airline", old_airline);
                    data.put("type", "B");

                } else if (is_delete) {
                    line_list.remove(old_airline);
                    data.put("mc_airline", mc_airline);
                    data.put("old_airline", old_airline);
                    data.put("type", "C");

                } else {
                    if (!is_modify && line_list.size() < 1) line_list.add("기본값");
                    line_list.add(mc_airline);
                    data.put("mc_airline", mc_airline);
                    data.put("type", "A");
                }

                for (int i = 0; i < line_list.size(); i++) {
                    if (i == 0) {
                        cp_airline = line_list.get(i);
                    } else if (!line_list.get(i).equals("")) {
                        cp_airline = cp_airline + "," + line_list.get(i);
                    }
                }

                data.put("cp_airline", cp_airline);
                Log.d("데이터@@@", data.toString());
                new ApiClient(data, "proc_admin_management_airline", 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_management_airline")) {
                        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();
                            clickListener.clickBtn();
                            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();
                }

                airline_modifyPB.setVisibility(View.GONE);
            }
        };
    }
}


