package kr.co.compcarecompany.Fragment.Main;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
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.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ReportPublishSettingAdapter;
import kr.co.compcarecompany.Util.Adapter.ReportPublishSettingTabAdapter;
import kr.co.compcarecompany.Util.Alarm.PublishMonthAlarmReceiver;
import kr.co.compcarecompany.Util.Alarm.PublishWeekAlarmReceiver;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.MyOnItemClick;

public class Report_Publish_Setting_Fragment extends Fragment implements MyOnItemClick {

    private Handler handler;
    private FragmentActivity fa;
    private ArrayList<MachineItem> machine_item;
    private RecyclerView report_publish_listRV, company_list_tabRV;
    private TextView report_publish_closeTV, report_publish_saveTV, cp_nameTV, save_chargeTV;
    private ReportPublishSettingAdapter adapter;
    private String ag_idx, pt_idx, cp_idx;
    private ArrayItem<CompanyData> company_list;
    private ReportPublishSettingTabAdapter tabAdapter;
    private EditText basic_chargeET;

    public Report_Publish_Setting_Fragment(Handler handler, String ag_idx, String pt_idx) {
        this.handler = handler;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
    }

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

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

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

        report_publish_listRV = v.findViewById(R.id.report_publish_listRV);
        report_publish_closeTV = v.findViewById(R.id.report_publish_closeTV);
        report_publish_saveTV = v.findViewById(R.id.report_publish_saveTV);
        company_list_tabRV = v.findViewById(R.id.company_list_tabRV);
        basic_chargeET = v.findViewById(R.id.basic_chargeET);
        cp_nameTV = v.findViewById(R.id.cp_nameTV);
        save_chargeTV = v.findViewById(R.id.save_chargeTV);

        init_Listener();
        init_Handler();
        Get_machines();

        return v;
    }

    private void Get_machines() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("pt_idx", pt_idx);
        new ApiClient(data, "proc_get_partner_machines", handler);
    }

    void init_Listener() {

        //전기요금 저장버튼 클릭리스너
        save_chargeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Common.getInstance().setPref(Objects.requireNonNull(getContext()), cp_idx + "report_publish", basic_chargeET.getText().toString());
                Toast.makeText(getContext(), cp_nameTV.getText() + " 기본 전기요금이 저장되었습니다\n소비전력 레포트 발행시 저장된 요금으로 계산됩니다", Toast.LENGTH_SHORT).show();

            }
        });

        //설정 저장버튼 클릭리스너
        report_publish_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String mc_idx_list = "";
                String rp_yn_list = "";
                String rp_period_list = "";

                for (int i = 0; i < machine_item.size(); i++) {

                    if (mc_idx_list.length() > 0)
                        mc_idx_list = mc_idx_list + ", " + machine_item.get(i).getMcIdx();
                    else mc_idx_list = machine_item.get(i).getMcIdx();

                    if (rp_yn_list.length() > 0)
                        rp_yn_list = rp_yn_list + ", " + machine_item.get(i).getRpYn();
                    else rp_yn_list = machine_item.get(i).getRpYn();

                    if (rp_period_list.length() > 0)
                        rp_period_list = rp_period_list + ", " + machine_item.get(i).getRpPeriod();
                    else rp_period_list = machine_item.get(i).getRpPeriod();
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("mc_idx_list", mc_idx_list);
                data.put("rp_yn_list", rp_yn_list);
                data.put("rp_period_list", rp_period_list);
                data.put("rp_charge", basic_chargeET.getText().toString());
                data.put("mb_idx", fa.userItem.getArrayitem().getMbIdx());
                data.put("cp_idx", cp_idx);

                new ApiClient(data, "proc_save_report_publish_setting", handler);
            }
        });

        //닫기버튼 클릭리스너
        report_publish_closeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
    }


    void init_Handler() {
        handler = new Handler() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {
                    if (url.equals("proc_get_partner_machines")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        company_list = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                        }.getType());

                        if (company_list.isSuccess()) {

                            tabAdapter = new ReportPublishSettingTabAdapter(getContext(), Report_Publish_Setting_Fragment.this::onClick);
                            company_list_tabRV.setAdapter(tabAdapter);
                            company_list.getArrayitem().get(0).setSelected(true);
                            cp_idx = company_list.getArrayitem().get(0).getCpIdx();
                            tabAdapter.addItems(company_list.getArrayitem());

                            machine_item = company_list.get(0).getMachineAll();
                            cp_nameTV.setText("[ " + company_list.get(0).getCpName() + " ]");
                            adapter = new ReportPublishSettingAdapter(getContext(), new ReportPublishSettingAdapter.completeListener() {
                                @Override
                                public void yn_clickBtn(String mc_idx, String isChecked, int position) {
                                    machine_item.get(position).setRpYn(isChecked);
                                }

                                @Override
                                public void period_clickBtn(String mc_idx, String period, int position) {
                                    machine_item.get(position).setRpPeriod(period);
                                }
                            });
                            report_publish_listRV.setHasFixedSize(true);
                            report_publish_listRV.setAdapter(adapter);

                            adapter.addItem(machine_item);

                            if (machine_item.get(0).getRpCharge() != null) {
                                basic_chargeET.setText(machine_item.get(0).getRpCharge());

                            } else {
                                basic_chargeET.setText("110");
                            }

                        } else {
                            basic_chargeET.setText("110");
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                    } else if (url.equals("proc_save_report_publish_setting")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        ArrayItem<MachineItem> rp_data = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineItem>>() {
                        }.getType());

                        if (rp_data.isSuccess()) {

                            AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
                            Intent week_intent = new Intent(getContext(), PublishWeekAlarmReceiver.class);
                            PendingIntent week_alarmIntent = PendingIntent.getBroadcast(getContext(), 7, week_intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
                            alarmManager.cancel(week_alarmIntent);

                            if (Integer.parseInt(rp_data.get(0).getWeekCnt()) > 0) {

                                try {
                                    AlarmManager.AlarmClockInfo ac = new AlarmManager.AlarmClockInfo(Common.getInstance().getTimeForAlarm("week"), week_alarmIntent);
                                    alarmManager.setAlarmClock(ac, week_alarmIntent);
                                    Common.getInstance().setPref(getContext(), "week_report_publish", true);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }

                            } else {
                                Common.getInstance().delPref(getContext(), "week_report_publish");
                            }

                            Intent month_intent = new Intent(getContext(), PublishMonthAlarmReceiver.class);
                            PendingIntent month_alarmIntent = PendingIntent.getBroadcast(getContext(), 31, month_intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
                            alarmManager.cancel(month_alarmIntent);

                            if (Integer.parseInt(rp_data.get(0).getMonthCnt()) > 0) {

                                try {
                                    AlarmManager.AlarmClockInfo ac = new AlarmManager.AlarmClockInfo(Common.getInstance().getTimeForAlarm("month"), month_alarmIntent);
                                    alarmManager.setAlarmClock(ac, month_alarmIntent);
                                    Common.getInstance().setPref(getContext(), "month_report_publish", true);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }

                            } else {
                                Common.getInstance().delPref(getContext(), "month_report_publish");
                            }
                            Common.getInstance().customToastShow_short(getContext(), cp_nameTV.getText() + " 소비전력 레포트 발행설정을 저장했습니다\n발행된 레포트는 사진첩에 저장할 수 있습니다", fa);
                        }
                    }

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

            }
        };
    }

    @Override
    public void onClick(Bundle value) {

        int position = Integer.parseInt(value.getString("item_position"));
        for (int i = 0; i < company_list.size(); i++) {
            company_list.getArrayitem().get(i).setSelected(i == position);
        }

        cp_nameTV.setText("[ " + company_list.get(position).getCpName() + " ]");
        cp_idx = company_list.get(position).getCpIdx();
        tabAdapter.clearItem();
        tabAdapter.addItems(company_list.getArrayitem());
        machine_item = company_list.get(position).getMachineAll();
        if (machine_item.get(0).getRpCharge() != null)
            basic_chargeET.setText(machine_item.get(0).getRpCharge());
        else basic_chargeET.setText("110");
        adapter.addItem(machine_item);

    }
}
