package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.LimitLine;
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.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.MonitoringAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.ConvertTimeZone;

public class MonitoringDialog extends Dialog {

    private Context context;
    private RecyclerView monitorRV;
    private LineChart monitorLC;
    private String mac;
    private String type, chart_type;
    private String period, group_period;
    private TextView monitor_dayTV, monitor_monthTV, monitor_weekendTV, max_visibleTV, max_goneTV,
            value_typeTV, monitor_select_dateTV, monitor_selected_dateTV, monitor_30minTV, consumption_averageTV;
    private ImageView pri_hour_dataIV, pri_min_dataIV, next_hour_dataIV, next_min_dataIV;
    private Handler hdr;
    private ArrayList<Entry> entries = new ArrayList<>();
    private ArrayList<String> num_list = new ArrayList<>();
    private ArrayList<String> time_list = new ArrayList<>();
    private String monitoring_time;
    private String monitoring_data;
    private ArrayList<MonitoringData> items = new ArrayList<>();
    private boolean exist_maxLine = true;
    private boolean exist_period = true;
    private MyPickerDialog.MyPickerDialogListener callbackMethod;
    private LinearLayout monitor_select_dateLL, select_dateLL, select_monthLL;
    private ProgressBar monitorPB;
    private long start_date;
    private String data_max;
    private Date startDate = null;
    private Date endDate = null;
    private String monitor_time, time;
    private Spinner select_monthSN;
    private int this_month, this_year;
    private MonitoringAdapter adapter;

    private ArrayItem<MonitoringData> monitoringArray;
    private MonitoringData monitoringData;
    private MachineItem machineItem;

    public MonitoringDialog(@NonNull Context context, String ag_idx, String pt_idx, String cp_idx, String mc_idx, String type, String mac, MachineItem machineItem) {
        super(context);
        this.context = context;
        this.chart_type = type;
        this.mac = mac;
        this.machineItem = machineItem;
    }

    public MonitoringDialog(@NonNull Context context, String type, MachineItem machineItem, String time) {
        super(context);
        this.context = context;
        this.chart_type = type;
        this.machineItem = machineItem;
        this.time = time;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dlg_monitoring_detail);

        MyApplication.stop_ui_change = true;

        monitorRV = findViewById(R.id.monitorRV);
        monitorLC = findViewById(R.id.monitorLC);
        monitor_dayTV = findViewById(R.id.monitor_dayTV);
        monitor_monthTV = findViewById(R.id.monitor_monthTV);
        monitor_weekendTV = findViewById(R.id.monitor_weekendTV);
        max_visibleTV = findViewById(R.id.max_visibleTV);
        max_goneTV = findViewById(R.id.max_goneTV);
        value_typeTV = findViewById(R.id.value_typeTV);
        monitor_select_dateTV = findViewById(R.id.monitor_select_dateTV);
        monitor_select_dateLL = findViewById(R.id.monitor_select_dateLL);
        monitorPB = findViewById(R.id.monitorPB);
        monitor_selected_dateTV = findViewById(R.id.monitor_selected_dateTV);
        pri_hour_dataIV = findViewById(R.id.pri_hour_dataIV);
        pri_min_dataIV = findViewById(R.id.pri_min_dataIV);
        next_hour_dataIV = findViewById(R.id.next_hour_dataIV);
        next_min_dataIV = findViewById(R.id.next_min_dataIV);
        select_dateLL = findViewById(R.id.select_dateLL);
        monitor_30minTV = findViewById(R.id.monitor_30minTV);
        select_monthLL = findViewById(R.id.select_monthLL);
        select_monthSN = findViewById(R.id.select_monthSN);
        consumption_averageTV = findViewById(R.id.consumption_averageTV);

        if (chart_type.equals("power_consumption"))
            consumption_averageTV.setVisibility(View.VISIBLE);

        //월 스피너 초기화
        Calendar calendar = Calendar.getInstance();
        this_year = calendar.get(Calendar.YEAR);
        this_month = calendar.get(Calendar.MONTH) + 1;
        ArrayAdapter<CharSequence> month_adapter = ArrayAdapter.createFromResource(getContext(), R.array.month, R.layout.custom_spinner_item_purple);
        select_monthSN.setAdapter(month_adapter);
        select_monthSN.setOnItemSelectedListener(null);
        select_monthSN.setSelection(this_month - 1);

        if (TextUtils.isEmpty(time)) {

            SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA);
            Date date = new Date();
            String today = dataFormat.format(date);
            try {
                startDate = dataFormat.parse(today);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {

            mac = machineItem.getMcIotMac();

            SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA);
            SimpleDateFormat dataFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.KOREA);
            Date date = new Date();
            try {
                date = dataFormat2.parse(time);
                String con = dataFormat.format(date);
                startDate = dataFormat.parse(con);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            type = "day";
            exist_maxLine = true;
            exist_period = true;
            select_dateLL.setVisibility(View.VISIBLE);
            monitor_dayTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
            monitor_dayTV.setTextColor(Color.parseColor("#9134A1"));
            monitor_monthTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
            monitor_monthTV.setTextColor(Color.parseColor("#9134A1"));
            monitor_30minTV.setBackgroundResource(R.color.color_bg_purple);
            monitor_30minTV.setTextColor(getContext().getResources().getColor(R.color.white));
            monitor_time = "30";

            max_visibleTV.setVisibility(View.GONE);
            max_goneTV.setVisibility(View.VISIBLE);
        }

        endDate = startDate;
        monitor_time = "30";

        period = startDate.getTime() + "000000 - " + monitor_time + "m";
        group_period = startDate.getTime() + "000000";

        start_date = startDate.getTime();

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.95f);
        int y = (int) (size.y * 0.95f);

        thisWindow.setLayout(x, y);

        init_Handler();
        init_Listener();
        Get_ChartData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        MyApplication.stop_ui_change = false;
    }

    void Get_ChartData() {
        //차트데이터
        monitorPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("mac", mac);
        if (!TextUtils.isEmpty(period) && !TextUtils.isEmpty(group_period)) {
            data.put("period", period);
            data.put("group_period", group_period);
        }

        new ApiClient(data, "proc_monitoring", hdr);
    }

    void Get_Month_ChartData() {
        //차트데이터
        monitorPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("mac", mac);
        data.put("period", period);
        data.put("group_period", group_period);
        data.put("type", "month");
        new ApiClient(data, "proc_monitoring", hdr);
    }


    private void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                String url = msg.getData().getString("url");
                Log.e("init_Handler", url.toString());

                if (url.equals("proc_monitoring")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    monitoringArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                    }.getType());

                    if (monitoringArray.isSuccess()) {

                        int size = monitoringArray.size();

                        num_list.clear();
                        time_list.clear();
                        items.clear();

                        float consumption_sum = 0;
                        int consumption_cnt = 0;

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

                            monitoringData = monitoringArray.getArrayitem().get(i);

                            String value = null;

                            switch (chart_type) {

                                case "power_consumption":

                                    if (monitoringData.getPowerConsumption() != null) {
                                        String consumption = Common.getInstance().isNullToZero(monitoringData.getPowerConsumption());
                                        float val = Float.parseFloat(Common.getInstance().valueConvert1(consumption));

                                        if (val > 1000) {
                                            value = (int) (val / 1000) + "";
                                            consumption_sum = consumption_sum + Float.parseFloat(value);
                                            consumption_cnt++;
                                        }
                                    }

                                    data_max = "100";
                                    break;

                                case "current1":
                                    if (monitoringData.getCurrent1() != null)
                                        value = monitoringData.getCurrent1();

                                    if (machineItem.getMcCurrent1Max() != null && !machineItem.getMcCurrent1Max().equals("0")) {
                                        data_max = machineItem.getMcCurrent1Max();

                                    } else {
                                        data_max = "75";
                                    }
                                    break;

                                case "current2":
                                    if (monitoringData.getCurrent2() != null)
                                        value = monitoringData.getCurrent2();

                                    if (machineItem.getMcCurrent2Max() != null && !machineItem.getMcCurrent2Max().equals("0")) {
                                        data_max = machineItem.getMcCurrent2Max();

                                    } else {
                                        data_max = "75";
                                    }
                                    break;

                                case "current3":
                                    if (monitoringData.getCurrent3() != null)
                                        value = monitoringData.getCurrent3();

                                    if (machineItem.getMcCurrent3Max() != null && !machineItem.getMcCurrent3Max().equals("0")) {
                                        data_max = machineItem.getMcCurrent3Max();

                                    } else {
                                        data_max = "75";
                                    }
                                    break;

                                case "temperaturePt":
                                    if (monitoringData.getTempPt100() != null)
                                        value = monitoringData.getTempPt100();

                                    if (machineItem.getMcTempPtMax() != null && !machineItem.getMcTempPtMax().equals("0")) {
                                        data_max = machineItem.getMcTempPtMax();

                                    } else {
                                        data_max = "120";
                                    }
                                    break;

                                case "temperatureNtc":
                                    if (monitoringData.getTempNtc() != null)
                                        value = monitoringData.getTempNtc();

                                    if (machineItem.getMcTempNtcMax() != null && !machineItem.getMcTempNtcMax().equals("0")) {
                                        data_max = machineItem.getMcTempNtcMax();

                                    } else {
                                        data_max = "120";
                                    }
                                    break;

                                case "temperatureNtc2":
                                    if (monitoringData.getTempNtc2() != null)
                                        value = monitoringData.getTempNtc2();

                                    if (machineItem.getMcTempNtc2Max() != null && !machineItem.getMcTempNtc2Max().equals("0")) {
                                        data_max = machineItem.getMcTempNtc2Max();

                                    } else {
                                        data_max = "120";
                                    }
                                    break;

                                case "pressure1":
                                    if (monitoringData.getPressure1() != null)
                                        value = monitoringData.getPressure1();

                                    if (machineItem.getMcPressure1Max() != null && !machineItem.getMcPressure1Max().equals("0")) {
                                        data_max = machineItem.getMcPressure1Max();

                                    } else {
                                        data_max = "10";
                                    }
                                    break;

                                case "pressure2":
                                    if (monitoringData.getPressure2() != null)
                                        value = monitoringData.getPressure2();

                                    if (machineItem.getMcPressure2Max() != null && !machineItem.getMcPressure2Max().equals("0")) {
                                        data_max = machineItem.getMcPressure2Max();

                                    } else {
                                        data_max = "10";
                                    }
                                    break;

                                case "pressure3":
                                    if (monitoringData.getPressure3() != null)
                                        value = monitoringData.getPressure3();

                                    if (machineItem.getMcPressure3Max() != null && !machineItem.getMcPressure3Max().equals("0")) {
                                        data_max = machineItem.getMcPressure3Max();

                                    } else {
                                        data_max = "10";
                                    }
                                    break;

                                default:
                                    value = null;
                                    data_max = "0";
                            }

                            num_list.add(Common.getInstance().valueConvert1(value));

                            ConvertTimeZone timeZone = new ConvertTimeZone();
                            String str = "";

                            try {
                                str = timeZone.convertKoreaTimeS(monitoringData.getTime());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            if (exist_period) {
                                monitoring_time = str.substring(11);
                                items = monitoringArray.getArrayitem();

                            } else if (type != null && type.equals("month")) {
                                monitoring_time = str.substring(8, 10);
                                items.add(monitoringArray.getArrayitem().get(i));
                            }

                            time_list.add(monitoring_time);
                        }

                        if (consumption_sum > 0) {

                            if (type != null && type.equals("month")) {
                                consumption_averageTV.setText("월 평균 : " + Common.getInstance().valueConvert1(consumption_sum / consumption_cnt + "") + "kW");
                            } else {
                                consumption_averageTV.setText("현재 평균 : " + Common.getInstance().valueConvert1(consumption_sum / consumption_cnt + "") + "kW");
                            }
                        }

                        setLineChart(monitorLC, num_list);
                        set_Contents();

                    } else {
                        Toast.makeText(getContext(), "해당시간에 저장된 데이터가 없습니다\n시간을 조정하여 데이터를 조회해보세요", Toast.LENGTH_SHORT).show();
                        monitorLC.clear();
                        if (adapter != null) adapter.clearItems();
                        monitorPB.setVisibility(View.GONE);
                        exist_maxLine = false;
                    }
                }
            }
        };
    }

    private void set_Contents() {

        adapter = new MonitoringAdapter(getContext(), type, chart_type, machineItem);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        monitorRV.setLayoutManager(layoutManager);

        if (TextUtils.isEmpty(period) || exist_period) {

            adapter.addItems(items);

            switch (chart_type) {
                case "power_consumption":
                    value_typeTV.setText("전력");
                    break;
                case "current1":
                case "current2":
                case "current3":
                    value_typeTV.setText("전류");
                    break;
                case "pressure1":
                case "pressure2":
                case "pressure3":
                    value_typeTV.setText("압력");
                    break;
                case "temperatureNtc":
                case "temperatureNtc2":
                case "temperaturePt":
                    value_typeTV.setText("온도");
                    break;
            }

        } else if (!TextUtils.isEmpty(type) && type.equals("month")) {

            adapter.addItems(items);

            switch (chart_type) {
                case "power_consumption":
                    value_typeTV.setText("전력(1일 평균)");
                    break;
                case "current1":
                case "current2":
                case "current3":
                    value_typeTV.setText("전류(1일 평균)");
                    break;
                case "pressure1":
                case "pressure2":
                case "pressure3":
                    value_typeTV.setText("압력(1일 평균)");
                    break;
                case "temperatureNtc":
                case "temperatureNtc2":
                case "temperaturePt":
                    value_typeTV.setText("온도(1일 평균)");
                    break;
            }
        }

        monitorRV.setAdapter(adapter);

        ConvertTimeZone timeZone = new ConvertTimeZone();
        String time = "";

        try {
            time = timeZone.convertKoreaTimeM(monitoringArray.getArrayitem().get(0).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        monitor_select_dateTV.setText(time);
        monitorPB.setVisibility(View.GONE);
    }

    private void init_Listener() {

        if (monitorPB.getVisibility() == View.VISIBLE) {
            Toast.makeText(context, "데이터를 가져오는 중입니다...", Toast.LENGTH_SHORT).show();
            return;
        }

        max_visibleTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                max_goneTV.setVisibility(View.VISIBLE);
                max_visibleTV.setVisibility(View.GONE);

                exist_maxLine = true;

                float max = monitorLC.getLineData().getYMax();
                float min = monitorLC.getLineData().getYMin();
                drawMax(monitorLC, max, min);
            }
        });

        max_goneTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                max_visibleTV.setVisibility(View.VISIBLE);
                max_goneTV.setVisibility(View.GONE);

                exist_maxLine = false;

                float max = monitorLC.getLineData().getYMax();
                float min = monitorLC.getLineData().getYMin();
                drawMax(monitorLC, max, min);
            }
        });

        monitor_dayTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //1분 간격차트
                type = "day";
                exist_maxLine = true;
                exist_period = true;
                select_dateLL.setVisibility(View.VISIBLE);
                monitor_dayTV.setBackgroundResource(R.drawable.bg_round_purple_except_right);
                monitor_dayTV.setTextColor(Color.WHITE);
                monitor_monthTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                monitor_monthTV.setTextColor(Color.parseColor("#9134A1"));
                monitor_select_dateTV.setText("날짜를 선택하세요.");
                monitor_30minTV.setBackgroundResource(R.color.white);
                monitor_30minTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                monitor_time = "1";

                select_monthLL.setVisibility(View.GONE);
                max_visibleTV.setVisibility(View.GONE);
                max_goneTV.setVisibility(View.VISIBLE);
            }
        });

        monitor_30minTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //30분 간격차트
                type = "day";
                exist_maxLine = true;
                exist_period = true;
                select_dateLL.setVisibility(View.VISIBLE);
                monitor_dayTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
                monitor_dayTV.setTextColor(Color.parseColor("#9134A1"));
                monitor_monthTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                monitor_monthTV.setTextColor(Color.parseColor("#9134A1"));
                monitor_select_dateTV.setText("날짜를 선택하세요.");
                monitor_30minTV.setBackgroundResource(R.color.color_bg_purple);
                monitor_30minTV.setTextColor(getContext().getResources().getColor(R.color.white));
                monitor_time = "30";

                select_monthLL.setVisibility(View.GONE);
                max_visibleTV.setVisibility(View.GONE);
                max_goneTV.setVisibility(View.VISIBLE);
            }
        });

        monitor_monthTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //월간 차트
                type = "month";
                exist_maxLine = true;
                exist_period = false;
                select_dateLL.setVisibility(View.GONE);
                monitor_dayTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
                monitor_dayTV.setTextColor(Color.parseColor("#9134A1"));
                monitor_monthTV.setBackgroundResource(R.drawable.bg_round_purple_except_left);
                monitor_monthTV.setTextColor(Color.WHITE);
                monitor_select_dateTV.setText("");
                monitor_30minTV.setBackgroundResource(R.color.white);
                monitor_30minTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                select_monthLL.setVisibility(View.VISIBLE);
                max_visibleTV.setVisibility(View.GONE);
                max_goneTV.setVisibility(View.VISIBLE);

                select_monthSN.setSelection(this_month - 1);

            }
        });

        monitor_select_dateLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyPickerDialog mydialog = new MyPickerDialog(context);
                mydialog.setListener(callbackMethod);
                mydialog.show();
            }
        });

        callbackMethod = new MyPickerDialog.MyPickerDialogListener() {
            @Override
            public void clickBtn(HashMap<String, Integer> get_data) {

                int dayOfMonth = get_data.get("day");
                int monthOfYear = get_data.get("month");
                int year = get_data.get("year");
                int hour = get_data.get("hour");
                int min = get_data.get("min");

                String day = null;
                String month = null;
                String time_hour = null;
                String time_min = null;
                start_date = 0;

                if (dayOfMonth < 10) {
                    day = "0" + dayOfMonth;
                } else {
                    day = dayOfMonth + "";
                }

                if (monthOfYear < 10) {
                    month = "0" + monthOfYear;
                } else {
                    month = monthOfYear + "";
                }

                if (hour < 10) {
                    time_hour = "0" + hour;
                } else {
                    time_hour = hour + "";
                }

                if (min < 10) {
                    time_min = "0" + min;
                } else {
                    time_min = min + "";
                }

                monitor_select_dateTV.setText(year + "." + month + "." + day + ". " + time_hour + ":" + time_min);

                String convert = year + month + day + time_hour + time_min + "00";

                SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA);
                Date date = new Date();
                String today = dataFormat.format(date);

                try {
                    startDate = dataFormat.parse(convert);
                    endDate = dataFormat.parse(today);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                period = startDate.getTime() + "000000";
                group_period = startDate.getTime() + "000000 + " + monitor_time + "m";

                start_date = startDate.getTime();

                exist_period = true;
                type = "day";

                Get_ChartData();

            }
        };

        //이전 1시간 데이터 가져오기
        pri_hour_dataIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pri_hour_dataIV.setEnabled(false);

                long cal_hour = start_date - 3600000;
                start_date = cal_hour;

                period = start_date + "000000";
                group_period = start_date + "000000 + " + monitor_time + "m";

                exist_period = true;
                type = "day";

                Get_ChartData();

                pri_hour_dataIV.setEnabled(true);
            }
        });

        //이전 1분 데이터 가져오기
        pri_min_dataIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pri_min_dataIV.setEnabled(false);

                long cal_hour = start_date - (60000 * Integer.parseInt(monitor_time));
                start_date = cal_hour;

                period = start_date + "000000";
                group_period = start_date + "000000 + " + monitor_time + "m";

                exist_period = true;
                type = "day";

                Get_ChartData();

                pri_min_dataIV.setEnabled(true);
            }
        });

        //다음 1분 데이터 가져오기
        next_min_dataIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                next_min_dataIV.setEnabled(false);

                long cal_hour = start_date + (60000 * Integer.parseInt(monitor_time));

                if (cal_hour > endDate.getTime()) {
                    start_date = endDate.getTime();

                } else {
                    start_date = cal_hour;
                }

                period = start_date + "000000";
                group_period = start_date + "000000 + " + monitor_time + "m";

                exist_period = true;
                type = "day";

                Get_ChartData();

                next_min_dataIV.setEnabled(true);
            }
        });

        //다음 1시간 데이터 가져오기
        next_hour_dataIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                next_hour_dataIV.setEnabled(false);

                long cal_hour = start_date + 3600000;

                if (cal_hour > endDate.getTime()) {
                    start_date = endDate.getTime();

                } else {
                    start_date = cal_hour;
                }

                period = start_date + "000000";
                group_period = start_date + "000000 + " + monitor_time + "m";

                exist_period = true;
                type = "day";

                Get_ChartData();

                next_hour_dataIV.setEnabled(true);
            }
        });

        select_monthSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                type = "month";

                if (position + 1 > this_month) {
                    Common.getInstance().toastShow(context, "현재보다 미래의 일자는 선택할 수 없습니다.");
                    select_monthSN.setSelection(this_month - 1);
                }

                try {
                    String first = Common.getInstance().getDateOfMonth(this_year, position + 1, "first");
                    String last = Common.getInstance().getDateOfMonth(this_year, position + 1, "last");

                    period = first;
                    group_period = last;
                    Get_Month_ChartData();

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

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

            }
        });
    }

    private void setLineChart(LineChart lineChart, ArrayList<String> number) {
        entries = new ArrayList<>();

        for (int i = 0; i < number.size(); i++) {
            entries.add(new Entry(i, Float.parseFloat(number.get(i))));
        }

        String line_color = "#82bb6b";

        LineDataSet lineDataSet = new LineDataSet(entries, null);
        lineDataSet.setLineWidth(1);

        lineDataSet.setDrawFilled(true);
        lineDataSet.setFillColor(Color.parseColor("#e9ffe0"));

        lineDataSet.setCircleColor(Color.parseColor("#F7A400"));
        lineDataSet.setColor(Color.parseColor(line_color));
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setCircleRadius(2f);
        lineDataSet.setDrawCircles(true);
        lineDataSet.setDrawHorizontalHighlightIndicator(false);
        lineDataSet.setDrawHighlightIndicators(false);
        lineDataSet.setDrawValues(false);

        LineData lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
        lineChart.invalidate();

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setAxisLineColor(Color.WHITE);
        xAxis.setAxisLineWidth(1f);
        xAxis.setYOffset(5f);
        xAxis.setGranularityEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setTextSize(8f);

        lineChart.setScaleXEnabled(false);
        lineChart.setScaleYEnabled(false);

        if (exist_period) {
            lineChart.setTouchEnabled(true);
            lineChart.setPinchZoom(true);
            lineChart.setScaleEnabled(true);

            xAxis.setLabelCount(3, true);
            xAxis.setAxisMinimum(0);
            xAxis.setAxisMaximum(num_list.size() - 1);

            //마커뷰
            CustomMarkerView marker = new CustomMarkerView(context, R.layout.custom_marker, time_list, chart_type, number);
            marker.setChartView(lineChart);
            lineChart.setMarker(marker);

        } else if (!TextUtils.isEmpty(period) && !exist_period) {
            xAxis.setLabelCount(num_list.size(), true);
            xAxis.setAxisMinimum(0);
            xAxis.setAxisMaximum(num_list.size() - 1);
        }

        xAxis.setGridDashedLine(new DashPathEffect(new float[]{3, 3}, 0));
        ValueFormatter xAxisFormatter = new MonitoringDialog.TimeAxisValueFormatter(lineChart);
        xAxis.setValueFormatter(xAxisFormatter);

        YAxis yLAxis = lineChart.getAxisLeft();
        yLAxis.setTextColor(Color.WHITE);
        yLAxis.setAxisLineColor(Color.WHITE);
        yLAxis.setTextSize(11f);
        yLAxis.setDrawGridLines(true);

        float max = lineChart.getLineData().getYMax();
        float min = lineChart.getLineData().getYMin();

        drawMax(lineChart, max, min);

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

        lineChart.getAxisRight().setEnabled(false);
        lineChart.getLegend().setEnabled(false);
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setDrawGridBackground(false);

        lineChart.setDescription(null);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.notifyDataSetChanged();
        lineChart.fitScreen();

        lineChart.invalidate();
    }


    public class TimeAxisValueFormatter extends ValueFormatter {

        BarLineChartBase<?> chart;

        TimeAxisValueFormatter(BarLineChartBase<?> chart) {
            this.chart = chart;
        }

        @Override
        public String getFormattedValue(float value) {

            String set_time = "";
            int match = (int) value;
            if (match > -1 && match < time_list.size()) set_time = time_list.get(match);
            return set_time;
        }
    }

    private void drawMax(LineChart lineChart, float max, float min) {

        YAxis yLAxis = lineChart.getAxisLeft();

        if (exist_maxLine) {

            LimitLine limit = new LimitLine(Float.parseFloat(data_max), "Max");
            limit.setLineWidth(2f);
            limit.enableDashedLine(10f, 10f, 0f);
            limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            limit.setTextSize(10f);
            limit.setTextColor(Color.WHITE);

            yLAxis.removeAllLimitLines();
            yLAxis.addLimitLine(limit);
            yLAxis.setAxisMaximum(Float.parseFloat(data_max) + 15f);
            yLAxis.setAxisMinimum(0);

            yLAxis.setLabelCount(5, true);

        } else {

            yLAxis.removeAllLimitLines();
            yLAxis.setAxisMaximum(max + 5);
            yLAxis.setAxisMinimum(min - 5);
            yLAxis.setLabelCount(10, false);
        }

        if (chart_type.equals("temperatureNtc") || chart_type.equals("temperatureNtc2") || chart_type.equals("temperaturePt")) {
            if (min < 0) {
                yLAxis.setAxisMinimum(min);
            }
        }

        lineChart.fitScreen();
        lineChart.invalidate();
    }
}
