package kr.co.compcareworker.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.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
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.Date;
import java.util.HashMap;
import java.util.Locale;

import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.MonitoringAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.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;
    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 ArrayList<String> marker_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;
    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 ArrayItem<MonitoringData> monitoringArray;
    private MonitoringData monitoringData;
    private MachineItem machineItem;

    public MonitoringDialog(@NonNull Context context, String ag_id, 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, String mac, MachineItem machineItem, String time) {
        super(context);
        this.context = context;
        this.chart_type = type;
        this.mac = mac;
        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);

        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 {

            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) {
            }

        }

        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);
    }

    private 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");
                    Log.e("init_Handler", url.toString());

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

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            monitoringArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                            }.getType());

                            int size = monitoringArray.size();

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

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

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

                                if (monitoringData != null && !monitoringData.equals(null)) {
                                    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 && !monitoringData.getCurrent1().equals("0")) {
                                                value = monitoringData.getCurrent1();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcCurrent1Max())) {
                                                data_max = machineItem.getMcCurrent1Max();

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

                                        case "current2":
                                            if (monitoringData.getCurrent2() != null && !monitoringData.getCurrent2().equals("0")) {
                                                value = monitoringData.getCurrent2();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcCurrent2Max())) {
                                                data_max = machineItem.getMcCurrent2Max();

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

                                        case "current3":
                                            if (monitoringData.getCurrent3() != null && !monitoringData.getCurrent3().equals("0")) {
                                                value = monitoringData.getCurrent3();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcCurrent3Max())) {
                                                data_max = machineItem.getMcCurrent3Max();

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

                                        case "temperaturePt":
                                            if (monitoringData.getTempPt100() != null && !monitoringData.getTempPt100().equals("0")) {
                                                value = monitoringData.getTempPt100();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcTempPtMax())) {
                                                data_max = machineItem.getMcTempPtMax();

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

                                        case "temperatureNtc":
                                            if (monitoringData.getTempNtc() != null && !monitoringData.getTempNtc().equals("0")) {
                                                value = monitoringData.getTempNtc();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcTempNtcMax())) {
                                                data_max = machineItem.getMcTempNtcMax();

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

                                        case "temperatureNtc2":
                                            if (monitoringData.getTempNtc2() != null && !monitoringData.getTempNtc2().equals("0")) {
                                                value = monitoringData.getTempNtc2();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcTempNtc2Max())) {
                                                data_max = machineItem.getMcTempNtc2Max();

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

                                        case "pressure1":
                                            if (monitoringData.getPressure1() != null && !monitoringData.getPressure1().equals("0")) {
                                                value = monitoringData.getPressure1();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcPressure1Max())) {
                                                data_max = machineItem.getMcPressure1Max();

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

                                        case "pressure2":
                                            if (monitoringData.getPressure2() != null && !monitoringData.getPressure2().equals("0")) {
                                                value = monitoringData.getPressure2();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcPressure2Max())) {
                                                data_max = machineItem.getMcPressure2Max();

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

                                        case "pressure3":
                                            if (monitoringData.getPressure3() != null && !monitoringData.getPressure3().equals("0")) {
                                                value = monitoringData.getPressure3();

                                            } else {
                                                value = null;
                                            }

                                            if (!TextUtils.isEmpty(machineItem.getMcPressure3Max())) {
                                                data_max = machineItem.getMcPressure3Max();

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

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

                                    if (value != null) {
                                        monitoring_data = Common.getInstance().valueConvert(value);
                                        marker_list.add(Common.getInstance().valueConvert1(value));
                                    }

                                    if (value != null && monitoringData.getTime() != null) {

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

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

                                        if (TextUtils.isEmpty(period)) {

                                            monitoring_time = str.substring(11);
                                            num_list.add(monitoring_data);
                                            time_list.add(monitoring_time);
                                            items = monitoringArray.getArrayitem();

                                        } else {

                                            SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy.MM.dd");
                                            Date date = new Date();
                                            String today = formatter.format(date);

                                            if (exist_period) {
                                                monitoring_time = str.substring(11);
                                                num_list.add(monitoring_data);
                                                time_list.add(monitoring_time);
                                                items = monitoringArray.getArrayitem();

                                            } else if (period.equals("31d")) {

                                                String this_month = today.substring(0, 7) + ".01";
                                                monitoring_time = str.substring(8, 10);

                                                if (this_month.compareTo(str) == 0 || this_month.compareTo(str) < 0) {

                                                    num_list.add(monitoring_data);
                                                    time_list.add(monitoring_time);
                                                    items.add(monitoringArray.getArrayitem().get(i));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            setLineChart(monitorLC, num_list);
                            set_Contents();

                        } else {
                            Toast.makeText(getContext(), "데이터가 없습니다.", Toast.LENGTH_SHORT).show();
                            value_typeTV.setText("온도");
                            monitorPB.setVisibility(View.GONE);
                            exist_maxLine = false;
                        }
                    }
                }
            }
        };
    }

    private void set_Contents() {

        MonitoringAdapter 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 "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 (period.equals("31d")) {

            adapter.addItems(items);

            switch (chart_type) {
                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_main_except_right);
                monitor_dayTV.setTextColor(Color.WHITE);
                monitor_monthTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                monitor_monthTV.setTextColor(getContext().getResources().getColor(R.color.color_main));
                monitor_select_dateTV.setText("날짜를 선택하세요.");
                monitor_30minTV.setBackgroundResource(R.color.white);
                monitor_30minTV.setTextColor(getContext().getResources().getColor(R.color.color_main));
                monitor_time = "1";

                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(getContext().getResources().getColor(R.color.color_main));
                monitor_monthTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                monitor_monthTV.setTextColor(getContext().getResources().getColor(R.color.color_main));
                monitor_select_dateTV.setText("날짜를 선택하세요.");
                monitor_30minTV.setBackgroundResource(R.color.color_main);
                monitor_30minTV.setTextColor(getContext().getResources().getColor(R.color.white));
                monitor_time = "30";

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

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

                //월간 차트
                period = "31d";
                group_period = "1d";
                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(getContext().getResources().getColor(R.color.color_main));
                monitor_monthTV.setBackgroundResource(R.drawable.bg_round_main_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_main));

                Get_ChartData();

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

            }
        });

        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);
            }
        });
    }

    private void setLineChart(LineChart lineChart, ArrayList<String> number) {

        lineChart.clear();
        entries.clear();

        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);

        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);

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

        xAxis.setValueFormatter(xAxisFormatter);

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

        lineChart.invalidate();

        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, marker_list);
            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);

        }

        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();

    }


    public class TimeAxisValueFormatter extends ValueFormatter {

        TimeAxisValueFormatter(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {

            String set_time = "";
            int match = (int) value;

            int half = time_list.size() / 2;
            int last = time_list.size() - 1;

            if (TextUtils.isEmpty(period)) {

                if (match == 0) {

                    set_time = time_list.get(0);

                } else if (match == half - 1 || match == half || match == half + 1) {

                    set_time = time_list.get(half);

                } else if (match == last) {

                    set_time = time_list.get(last);

                }

            } else if (!TextUtils.isEmpty(period) && period.equals("31d")) {

                if (match > 0 && match < time_list.size()) {
                    set_time = time_list.get(match) + "";
                }

            } else if (!TextUtils.isEmpty(period) && exist_period) {

                if (match > 0 && match < time_list.size())
                    set_time = time_list.get(match) + "";

            } else {

                set_time = "" + ((int) value);
            }

            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();
    }
}
