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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
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.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.WebviewAct;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.CompanyData;
import kr.co.compcareworker.Data.Company.Machine.AlMachineDatum;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.MachineListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

@SuppressLint("ValidFragment")
public class Machine_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;
    String pt_idx;

    TextView add, add_line;
    RecyclerView list;
    MachineListRecyclerAdapter adapter;

    ArrayItem<CompanyData> items;

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

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

    @Override
    public void onResume() {
        super.onResume();
        Get_Contents();
    }

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

    public Machine_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_machine, container, false);

        add = v.findViewById(R.id.add);
        add_line = v.findViewById(R.id.add_line);
        list = v.findViewById(R.id.list);

        init_Handler();
        init_Listener();

        adapter = new MachineListRecyclerAdapter(getContext(), fa.userItem.getArrayitem().getAgency().getMbId(), fa.userItem.getArrayitem().getMbId());
        list.setAdapter(adapter);

        //Get_Contents();

        return v;
    }

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

    void Set_Contents() {
        adapter.clearItem();
        ArrayList<CompanyData> item = new ArrayList<>();
        item.addAll(items.getArrayitem());

        for (int i = 0; i < item.size(); i++) {
            ArrayList<AlMachineDatum> data = (ArrayList<AlMachineDatum>) item.get(i).getAlMachineData();
            for (int j = 0; j < data.size(); j++) {
                data.get(j).setPt_idx(item.get(i).getPtIdx());
                data.get(j).setPt_name(item.get(i).getPtName());
                data.get(j).setCp_idx(item.get(i).getCpIdx());
                data.get(j).setCp_name(item.get(i).getCpName());
                data.get(j).setCp_addr(item.get(i).getCpAddr());
                data.get(j).setCp_running_time(item.get(i).getCpRunningTime());
                data.get(j).setCp_running_day(item.get(i).getCpRunningDay());
            }
        }

        adapter.addItem(item);

        /*for (int i = 0; i < items.getArrayitem().size(); i++) {
            ArrayList<AlMachineDatum> data = new ArrayList<>();
            data.addAll(items.getArrayitem().get(i).getAlMachineData());
            for (int j = 0; j < data.size(); j++) {
                data.get(j).setPt_idx(items.getArrayitem().get(i).getPtIdx());
                data.get(j).setPt_name(items.getArrayitem().get(i).getPtName());
                data.get(j).setCp_idx(items.getArrayitem().get(i).getCpIdx());
                data.get(j).setCp_name(items.getArrayitem().get(i).getCpName());
                data.get(j).setCp_addr(items.getArrayitem().get(i).getCpAddr());
                data.get(j).setCp_running_time(items.getArrayitem().get(i).getCpRunningTime());
                data.get(j).setCp_running_day(items.getArrayitem().get(i).getCpRunningDay());
            }
            adapter.addItem(data);
        }*/
    }

    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_partner_machine_list")) {
                        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()) {
                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        }
                    }
                }
            }
        };
    }

    private void init_Listener() {
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String incodeUrl = URLEncoder.encode("https://agency.compcare.co.kr/setting/serial/write/" + pt_idx);
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "설치장소 추가");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });

        add_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String incodeUrl = URLEncoder.encode("https://agency.compcare.co.kr/setting/serial/airline_write/" + pt_idx + "?cp_idx=");
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "AIR-LINE 추가");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });
    }
}
