package kr.co.compcarecompany.Fragment.Main;

import android.app.NotificationManager;
import android.content.Context;
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.ProgressBar;
import android.widget.RelativeLayout;
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.PagerSnapHelper;
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.Calendar;
import java.util.Date;
import java.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ReportPublishAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class Report_Publish_Fragment extends Fragment {

    private Handler handler;
    private String type;
    private TextView publish_report_closeTV;
    private ProgressBar publish_reportPB;
    private RecyclerView publish_reportRV;
    private FragmentActivity fa;
    private RelativeLayout no_dataRL;

    public Report_Publish_Fragment(Handler handler, String type) {
        this.handler = handler;
        this.type = type;
    }

    @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, container, false);

        publish_report_closeTV = v.findViewById(R.id.publish_report_closeTV);
        publish_reportPB = v.findViewById(R.id.publish_reportPB);
        publish_reportRV = v.findViewById(R.id.publish_reportRV);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(publish_reportRV);
        no_dataRL = v.findViewById(R.id.no_dataRL);

        NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (type.equals("week")) {
            notificationManager.cancel(11117);
        } else {
            notificationManager.cancel(11131);
        }

        init_Handler();
        init_Listener();
        try {
            Get_publish_report_data();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return v;
    }

    void Get_publish_report_data() throws ParseException {

        publish_reportPB.setVisibility(View.VISIBLE);

        HashMap<String, String> data = new HashMap<>();
        data.put("mb_idx", fa.userItem.getArrayitem().getMbIdx());
        data.put("type", type);

        String start_date;
        String end_date;

        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);

        //지난주
        if (type.equals("week")) {
            start_date = Common.getInstance().getDateOfWeek(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.WEEK_OF_MONTH) - 1, "first", false);
            end_date = Common.getInstance().getDateOfWeek(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.WEEK_OF_MONTH) - 1, "last", false);

            //지난달
        } else {
            start_date = Common.getInstance().getDateOfMonth(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), "first");
            end_date = Common.getInstance().getDateOfMonth(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), "last");
        }

        data.put("start_date", start_date);
        data.put("end_date", end_date);

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

    void init_Listener() {

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

    void init_Handler() {

        handler = 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_report_publish2")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        ArrayItem<MachineItem> machine_item = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineItem>>() {
                        }.getType());

                        Calendar calendar = Calendar.getInstance();
                        ReportPublishAdapter adapter;

                        if (machine_item.isSuccess()) {

                            if (machine_item.size() > 1) {
                                Common.getInstance().customToastShow_short(getContext(), "좌우로 슬라이드해서 다른 레포트도 확인해보세요", fa);
                            }
                            no_dataRL.setVisibility(View.GONE);

                            if (type.equals("week")) {
                                calendar.add(Calendar.WEEK_OF_MONTH, -1);
                                adapter = new ReportPublishAdapter(getContext(), "week", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.WEEK_OF_MONTH));
                            } else {
                                calendar.add(Calendar.MONTH, -1);
                                adapter = new ReportPublishAdapter(getContext(), "month", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.WEEK_OF_MONTH));
                            }

                            publish_reportRV.setAdapter(adapter);
                            adapter.addItem(machine_item.getArrayitem());

                        } else {
                            publish_reportRV.setVisibility(View.GONE);
                            no_dataRL.setVisibility(View.VISIBLE);
                        }

                    }
                } else {
                    publish_reportRV.setVisibility(View.GONE);
                    no_dataRL.setVisibility(View.VISIBLE);
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();

                }

                if (type.equals("week")) {
                    Common.getInstance().delPref(getContext(), "week_report");
                } else {
                    Common.getInstance().delPref(getContext(), "month_report");
                }

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