package kr.co.compcarecompany.Fragment.Main;

import android.content.Context;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.ScrollView;
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.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

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.ElectricChargeCalculatorAdapter;
import kr.co.compcarecompany.Util.Adapter.MonitoringCompareReportAdapter;
import kr.co.compcarecompany.Util.Adapter.MonitoringCompareTitleAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.CaptureUtils;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.CustomMarkerView2;

public class Monitoring_Compare_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView compare_titleTV, compare_closeTV, compare_saveTV;
    private LineChart power_consumption_avgLC, power_consumption_sumLC;

    private String start_date, end_date;
    private ArrayItem<MachineItem> machine_item;
    private ProgressBar comparePB;
    private RecyclerView compare_titleRV, compare_reportRV, electronic_charge_calRV;
    private ArrayList<String> mc_idx_list;
    private MonitoringCompareTitleAdapter compare_title_adapter;
    private MonitoringCompareReportAdapter compare_report_adapter;
    private ElectricChargeCalculatorAdapter charge_cal_adapter;
    private ScrollView compareSV;

    public Monitoring_Compare_Fragment(Handler handler, ArrayList<String> mc_idx_list, String start_date, String end_date) {
        this.handler = handler;
        this.mc_idx_list = mc_idx_list;
        this.start_date = start_date;
        this.end_date = end_date;
    }

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

        compare_titleTV = v.findViewById(R.id.compare_titleTV);
        compare_closeTV = v.findViewById(R.id.compare_closeTV);
        power_consumption_avgLC = v.findViewById(R.id.power_consumption_avgLC);
        power_consumption_sumLC = v.findViewById(R.id.power_consumption_sumLC);
        compare_titleRV = v.findViewById(R.id.compare_titleRV);
        compare_reportRV = v.findViewById(R.id.compare_reportRV);
        comparePB = v.findViewById(R.id.comparePB);
        electronic_charge_calRV = v.findViewById(R.id.electronic_charge_calRV);
        compareSV = v.findViewById(R.id.compareSV);
        compare_saveTV = v.findViewById(R.id.compare_saveTV);

        comparePB.setVisibility(View.VISIBLE);

        init_Listener();
        init_Handler();
        try {
            Get_Compare_Data();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return v;
    }

    private void Get_Compare_Data() throws ParseException {

        //소비전력 데이터
        HashMap<String, String> data = new HashMap<>();
        String mc_idxs = mc_idx_list.toString();
        mc_idxs = mc_idxs.replace("[", "");
        mc_idxs = mc_idxs.replace("]", "");
        data.put("mc_idx_list", mc_idxs);
        data.put("start_date", Convert_time(start_date, true));
        data.put("end_date", Convert_time(end_date, false));
        new ApiClient(data, "proc_get_power_consumption_data", handler);
    }

    private String Convert_time(String ori_date, boolean is_start) throws ParseException {

        if (is_start) {
            ori_date = ori_date + ".000000";
        } else {
            ori_date = ori_date + ".235959";
        }

        SimpleDateFormat new_dataFormat = new SimpleDateFormat("yyyy.MM.dd.HHmmss", Locale.KOREA);
        Date date = new_dataFormat.parse(ori_date);

        return date.getTime() + "000000";
    }

    private void Set_Contents() {
        compare_titleTV.setText(start_date + " ~ " + end_date + " 소비전력 비교 레포트");

        compare_title_adapter = new MonitoringCompareTitleAdapter(getContext());
        compare_titleRV.setAdapter(compare_title_adapter);
        compare_title_adapter.addItem(machine_item.getArrayitem());

        compare_report_adapter = new MonitoringCompareReportAdapter(getContext());
        compare_reportRV.setAdapter(compare_report_adapter);
        compare_report_adapter.addItem(machine_item.getArrayitem());

        charge_cal_adapter = new ElectricChargeCalculatorAdapter(getContext());
        electronic_charge_calRV.setAdapter(charge_cal_adapter);
        charge_cal_adapter.addItem(machine_item.getArrayitem());

    }

    private void setSumLineChart(ArrayList<ArrayList<Entry>> valList, ArrayList<String> time_list, LineChart lineChart) {

        int[] colors = new int[]{getContext().getResources().getColor(R.color.color_bg_purple), getContext().getResources().getColor(R.color.bar_chart_green),
                getContext().getResources().getColor(R.color.pie_chart_green)};

        int[] circle_colors = new int[]{getContext().getResources().getColor(R.color.schedule_2), getContext().getResources().getColor(R.color.schedule_5),
                getContext().getResources().getColor(R.color.schedule4)};

        LineData lineData = new LineData();

        int val_size = 0;

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

            if (val_size < valList.size()) val_size = valList.get(i).size();

            LineDataSet lineDataSet = new LineDataSet(valList.get(i), (i + 1) + "번 기계");
            lineDataSet.setLineWidth(2);
            lineDataSet.setCircleRadius(2);
            lineDataSet.setDrawFilled(false);

            lineDataSet.setCircleColor(circle_colors[i]);
            lineDataSet.setColor(colors[i]);
            lineDataSet.setDrawCircleHole(false);
            lineDataSet.setDrawCircles(true);
            lineDataSet.setDrawHorizontalHighlightIndicator(false);
            lineDataSet.setDrawHighlightIndicators(false);
            lineDataSet.setDrawValues(false);
            lineDataSet.setValueTextSize(8f);

            lineData.addDataSet(lineDataSet);

            CustomMarkerView2 marker = new CustomMarkerView2(getContext(), R.layout.custom_marker, time_list);
            marker.setChartView(lineChart);
            lineChart.setMarker(marker);

        }

        lineChart.setData(lineData);

        Legend legend = lineChart.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setFormSize(9f);
        legend.setTextSize(8f);
        legend.setXEntrySpace(4f);

        XAxis xAxis = lineChart.getXAxis();
        ValueFormatter xAxisFormatter = new TimeAxisValueFormatter(lineChart, time_list);
        xAxis.setTextSize(8f);

        xAxis.setGranularityEnabled(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setGridDashedLine(new DashPathEffect(new float[]{3, 3}, 0));

        if (val_size > 20) {

            if (val_size % 2 == 0) {
                xAxis.setLabelCount((val_size / 2), false);

            } else {
                xAxis.setLabelCount((val_size / 2) + (val_size % 2), true);
            }

        } else {
            xAxis.setLabelCount(val_size, true);
        }

        xAxis.setValueFormatter(xAxisFormatter);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setGranularity(1f);

        YAxis yLAxis = lineChart.getAxisLeft();
        yLAxis.setTextColor(Color.BLACK);
        yLAxis.setDrawAxisLine(false);
        yLAxis.setDrawGridLines(false);
        yLAxis.setAxisLineColor(Color.BLACK);
        yLAxis.setLabelCount(5, true);
        yLAxis.setAxisMinimum(0f);

        YAxis yRAxis = lineChart.getAxisRight();
        yRAxis.setDrawLabels(false);
        yRAxis.setDrawAxisLine(false);
        yRAxis.setDrawGridLines(false);

        lineChart.setVisibleXRange(val_size, val_size);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getLegend().setEnabled(true);
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setDrawGridBackground(false);
        lineChart.setScaleXEnabled(false);
        lineChart.setScaleYEnabled(false);
        lineChart.setDescription(null);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setPinchZoom(true);
        lineChart.fitScreen();

        lineChart.invalidate();

    }

    private void setAvgLineChart(ArrayList<ArrayList<Entry>> valList, ArrayList<String> time_list, LineChart lineChart) {

        int[] colors = new int[]{getContext().getResources().getColor(R.color.color_bg_purple), getContext().getResources().getColor(R.color.bar_chart_green),
                getContext().getResources().getColor(R.color.pie_chart_green)};

        int[] circle_colors = new int[]{getContext().getResources().getColor(R.color.schedule_2), getContext().getResources().getColor(R.color.schedule_5),
                getContext().getResources().getColor(R.color.schedule4)};

        LineData lineData = new LineData();

        int val_size = 0;

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

            if (val_size < valList.size()) val_size = valList.get(i).size();

            LineDataSet lineDataSet = new LineDataSet(valList.get(i), (i + 1) + "번 기계");
            lineDataSet.setLineWidth(2);
            lineDataSet.setCircleRadius(2);
            lineDataSet.setDrawFilled(false);

            lineDataSet.setCircleColor(circle_colors[i]);
            lineDataSet.setColor(colors[i]);
            lineDataSet.setDrawCircleHole(false);
            lineDataSet.setDrawCircles(true);
            lineDataSet.setDrawHorizontalHighlightIndicator(false);
            lineDataSet.setDrawHighlightIndicators(false);
            lineDataSet.setDrawValues(false);
            lineDataSet.setValueTextSize(8f);

            lineData.addDataSet(lineDataSet);

            CustomMarkerView2 marker = new CustomMarkerView2(getContext(), R.layout.custom_marker, time_list);
            marker.setChartView(lineChart);
            lineChart.setMarker(marker);
        }

        lineChart.setData(lineData);

        Legend legend = lineChart.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setFormSize(9f);
        legend.setTextSize(8f);
        legend.setXEntrySpace(4f);

        XAxis xAxis = lineChart.getXAxis();
        ValueFormatter xAxisFormatter = new TimeAxisValueFormatter(lineChart, time_list);
        xAxis.setTextSize(8f);

        xAxis.setGranularityEnabled(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setGridDashedLine(new DashPathEffect(new float[]{3, 3}, 0));

        if (val_size > 20) {

            if (val_size % 2 == 0) {
                xAxis.setLabelCount((val_size / 2), false);

            } else {
                xAxis.setLabelCount((val_size / 2) + (val_size % 2), true);
            }

        } else {
            xAxis.setLabelCount(val_size, true);
        }

        xAxis.setValueFormatter(xAxisFormatter);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setGranularity(1f);

        YAxis yLAxis = lineChart.getAxisLeft();
        yLAxis.setTextColor(Color.BLACK);
        yLAxis.setDrawAxisLine(false);
        yLAxis.setDrawGridLines(false);
        yLAxis.setAxisLineColor(Color.BLACK);
        yLAxis.setLabelCount(5, true);
        yLAxis.setAxisMinimum(0f);

        YAxis yRAxis = lineChart.getAxisRight();
        yRAxis.setDrawLabels(false);
        yRAxis.setDrawAxisLine(false);
        yRAxis.setDrawGridLines(false);

        lineChart.setVisibleXRange(val_size, val_size);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getLegend().setEnabled(true);
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setDrawGridBackground(false);
        lineChart.setScaleXEnabled(false);
        lineChart.setScaleYEnabled(false);
        lineChart.setDescription(null);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setPinchZoom(true);
        lineChart.fitScreen();

        lineChart.invalidate();

    }

    public static class TimeAxisValueFormatter extends ValueFormatter {

        ArrayList<String> time_list;

        TimeAxisValueFormatter(BarLineChartBase<?> chart, ArrayList<String> time_list) {
            this.time_list = time_list;
        }

        @Override
        public String getFormattedValue(float value) {

            if (time_list.size() == 0) return "";

            int i = (int) value;
            if (i < time_list.size())
            return time_list.get(i).substring(3);
            else return "";
        }
    }

    void init_Listener() {

        compare_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CaptureUtils.captureView(compareSV, getContext());
            }
        });

        //확인버튼 클릭리스너
        compare_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_power_consumption_data")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        machine_item = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineItem>>() {
                        }.getType());

                        if (machine_item.isSuccess()) {

                            Set_Contents();
                            ArrayList<ArrayList<Entry>> entries_list = new ArrayList<>();
                            ArrayList<ArrayList<Entry>> avg_entries_list = new ArrayList<>();
                            ArrayList<String> time_list = new ArrayList<>();
                            ArrayList<String> sum_list = new ArrayList<>();

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

                                ArrayList<Entry> entries = new ArrayList<>();
                                ArrayList<Entry> avg_list = new ArrayList<>();

                                long sum = 0;

                                if (machine_item.getArrayitem().get(i).getPowerConsumptionData() != null) {

                                    time_list.clear();

                                    for (int k = 1; k < machine_item.getArrayitem().get(i).getPowerConsumptionData().size(); k++) {
                                        String consumption = Common.getInstance().isNullToZero(machine_item.getArrayitem().get(i).getPowerConsumptionData().get(k).getPowerConsumptionSum());
                                        int avg = Integer.parseInt(Common.getInstance().valueConvert(consumption));
                                        int count = Integer.parseInt(Common.getInstance().valueConvert(machine_item.getArrayitem().get(i).getPowerConsumptionData().get(k).getPowerCount()));
                                        if (count > 0) avg_list.add(new Entry(k - 1, avg /count));

                                        sum = sum + Integer.parseInt(Common.getInstance().valueConvert(consumption));
                                        String time = machine_item.getArrayitem().get(i).getPowerConsumptionData().get(k).getTime();
                                        time = time.substring(5, 10);
                                        time = time.replace("-", "/");
                                        time_list.add(time);

                                        if (sum >= 720) {
                                            entries.add(new Entry(k - 1, (int) sum / 720));
                                            sum_list.add((int) sum / 720 + "");
                                        } else {
                                            entries.add(new Entry(k - 1, 0));
                                            sum_list.add("0");
                                        }
                                    }

                                } else {
                                    entries.add(new Entry(0, 0));
                                    avg_list.add(new Entry(0, 0));
                                }

                                if (entries.size() > 0) {
                                    entries_list.add(entries);
                                    avg_entries_list.add(avg_list);
                                }
                            }

                            setSumLineChart(entries_list, time_list, power_consumption_sumLC);
                            setAvgLineChart(avg_entries_list, time_list, power_consumption_avgLC);

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                    }

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

            }
        };
    }
}
