package kr.co.compcareworker.Fragment.Machine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
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 androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

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.CompanyData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;

@SuppressLint("ValidFragment")
public class Add_Airline_Fragment extends Fragment {

    FragmentActivity fa;
    Handler handler, hdr;
    TextView airline_ptNameTV, airline_cpNameTV, airline_addressTV, airline_addAirlineTV, airline_backTV, airline_nextTV;
    Spinner airline_airlineSP;
    EditText airline_airlineET;
    String cp_idx, pt_idx, qr, airline, airline_str;
    ArrayItem_<CompanyData> items;
    CompanyData item;
    String[] airLine_array;
    ArrayAdapter<String> airLine_adapter;

    @SuppressLint("ValidFragment")
    public Add_Airline_Fragment(Handler handler, String cp_idx, String pt_idx, String qr) {
        this.handler = handler;
        this.cp_idx = cp_idx;
        this.pt_idx = pt_idx;
        this.qr = qr;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.frag_add_airline, container, false);

        airline_ptNameTV = v.findViewById(R.id.airline_ptNameTV);
        airline_cpNameTV = v.findViewById(R.id.airline_cpNameTV);
        airline_addressTV = v.findViewById(R.id.airline_addressTV);
        airline_addAirlineTV = v.findViewById(R.id.airline_addAirlineTV);
        airline_backTV = v.findViewById(R.id.airline_backTV);
        airline_nextTV = v.findViewById(R.id.airline_nextTV);
        airline_airlineSP = v.findViewById(R.id.airline_airlineSP);
        airline_airlineET = v.findViewById(R.id.airline_airlineET);

        init_Handler();
        Get_Contents();
        init_Listener();

        return v;
    }

    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        new ApiClient(data, "proc_company_view", hdr);
    }

    void Set_Contents() {

        airline_ptNameTV.setText(item.getPtName());
        airline_cpNameTV.setText(item.getCpName());
        airline_addressTV.setText(item.getCpAddr() + " " + item.getCpAddrSub());

        airline_str = item.getCpAirline();

        airLine_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

        if (TextUtils.isEmpty(airline_str)) {
            airline_str = "기본값";
        }

        airLine_array = airline_str.split(",");
        for (String s : airLine_array) {
            airLine_adapter.add(s);
        }

        airline_airlineSP.setAdapter(airLine_adapter);
    }

    void init_Listener() {

        //Air_Line 추가
        airline_addAirlineTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (airline_airlineET.getText().toString().equals("")) {
                    return;
                }

                airLine_adapter.add(airline_airlineET.getText().toString());
                airline_airlineSP.setAdapter(airLine_adapter);
                airline_airlineET.getText().clear();
                airline_airlineET.clearFocus();
            }
        });

        //선택한 Air_Line
        airline_airlineSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                airline = airline_airlineSP.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //취소
        airline_backTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        //다음
        airline_nextTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "머신 등록");
                intent.putExtra("type", "add_machine");
                intent.putExtra("value1", cp_idx);
                intent.putExtra("value2", pt_idx);
                intent.putExtra("value3", qr);
                intent.putExtra("value4", airline);
                intent.putExtra("value5", airline_str);
                startActivity(intent);
            }
        });

    }

    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_company_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        items = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                        }.getType());

                        if (items.isSuccess()) {
                            item = items.getArrayitem();
                            Set_Contents();

                        } else {

                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    }
                } else if (msg.what == -1) {

                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }
}
