package kr.co.compcarecompany.Util.Adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
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.charts.PieChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
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.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;

import java.util.ArrayList;
import java.util.Arrays;

import kr.co.compcarecompany.Activity.FragmentActivity;
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.Common;
import kr.co.compcarecompany.Util.CustomView.MachinePasswordDialog;
import kr.co.compcarecompany.Util.RoundedBarChart;

import static kr.co.compcarecompany.Activity.ActivityBasic.userItem;

public class EnterpriseProdAdapter extends RecyclerView.Adapter<EnterpriseProdAdapter.ItemViewHolder> {
    private Context context;

    private String agency_id, user_id, pt_idx, cp_idx, mc_idx, mac, current_max, temperature_max, pressure_max;
    private TextView lastDt;
    private ArrayList<Entry> entries = new ArrayList<>();
    private ArrayList<String> time_list = new ArrayList<>();

    private String temperature;
    private Float current;
    private String pressure;

    private String pop_type;
    boolean btnState = true;

    // adapter에 들어갈 list 입니다.
    private ArrayList<MachineItem> items = new ArrayList<>();
    private MonitoringData monitoringData;
    ArrayItem<MonitoringData> monitoringArray;

    private EnterpriseProdAdapter.clickListener clickListener;

    public interface clickListener {
        void clickBtn(Bundle bundle);
    }

    private EnterpriseProdAdapter.chartClickListener chartClickListener;

    public interface chartClickListener {
        void clickBtn(Bundle bundle);
    }

    private EnterpriseProdAdapter.timeClickListener timeClickListener;

    public interface timeClickListener {
        void clickBtn(Bundle bundle);
    }

    private EnterpriseProdAdapter.liveClickListener liveClickListener;

    public interface liveClickListener {
        void clickBtn(Bundle bundle);
    }

    EnterpriseProdAdapter(Context context, String agency_id, String user_id, EnterpriseProdAdapter.clickListener clickListener,
                          EnterpriseProdAdapter.chartClickListener chartClickListener, EnterpriseProdAdapter.timeClickListener timeClickListener,
                          EnterpriseProdAdapter.liveClickListener liveClickListener) {
        this.context = context;
        this.agency_id = agency_id;
        this.user_id = user_id;
        this.clickListener = clickListener;
        this.chartClickListener = chartClickListener;
        this.timeClickListener = timeClickListener;
        this.liveClickListener = liveClickListener;

    }

    @NonNull
    @Override
    public EnterpriseProdAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // LayoutInflater를 이용하여 전 단계에서 만들었던 item.xml을 inflate 시킵니다.
        // return 인자는 ViewHolder 입니다.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_enterprise_prod, parent, false);
        return new EnterpriseProdAdapter.ItemViewHolder(view);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onBindViewHolder(@NonNull EnterpriseProdAdapter.ItemViewHolder holder, final int position) {
        // Item을 하나, 하나 보여주는(bind 되는) 함수입니다.
        holder.onBind(items.get(position));
        holder.seq.setText(position + 1 + ".");

        holder.sw.setOnCheckedChangeListener(null);


        //LIVE 버튼 클릭리스너 >> EnterpriseRecyclerAdapter로 mac, del_flag 전달함.
        holder.enterprise_prod_playLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean do_monitoring;

                if (!items.get(position).isRunning()) {
                    items.get(position).setRunning(true);
                    holder.enterprise_prod_playLL.setBackgroundResource(R.drawable.border_blue_fill_white_round_30_stroke_2);
                    holder.enterprise_prod_playIV.setImageResource(R.drawable.icon_play_blue);
                    holder.enterprise_prod_playTV.setTextColor(context.getResources().getColor(R.color.light_blue));
                    do_monitoring = true;

                } else {
                    items.get(position).setRunning(false);
                    holder.enterprise_prod_playLL.setBackgroundResource(R.drawable.border_gray_fill_white_round_30_stroke_2);
                    holder.enterprise_prod_playIV.setImageResource(R.drawable.icon_play_gray);
                    holder.enterprise_prod_playTV.setTextColor(context.getResources().getColor(R.color.gray));
                    do_monitoring = false;
                }

                Bundle bundle = new Bundle();
                bundle.putString("mac", items.get(position).getMcIotMac());
                bundle.putString("del_flag", items.get(position).getDelFlag());
                bundle.putString("air_line", items.get(position).getMcAirline());
                bundle.putString("k", position + "");
                bundle.putBoolean("do_monitoring", do_monitoring);

                liveClickListener.clickBtn(bundle);
            }
        });

        // ON/Off 버튼 클릭 리스너
        holder.sw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                MyApplication.doing_toggle = true;

                //기계보안 비밀번호가 없을 경우 비밀번호 설정 페이지로 넘어감
                if (userItem.getArrayitem().getMbMachinePw() == null || userItem.getArrayitem().getMbMachinePw().equals("")) {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("설정된 기계보안 비밀번호가 없습니다.\n바로 설정하시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {

                            Intent intent = new Intent(context, FragmentActivity.class);
                            intent.putExtra("title", "기계보안");
                            intent.putExtra("type", "password_setting");
                            intent.putExtra("value1", userItem.getArrayitem().getMbMachinePw());
                            context.startActivity(intent);
                            dialog.dismiss();

                        }
                    });
                    dialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            MyApplication.doing_toggle = false;
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                }

                //기계 비밀번호 확인 다이얼로그
                MachinePasswordDialog dialog = new MachinePasswordDialog(context, userItem.getArrayitem().getMbMachinePw(), new MachinePasswordDialog.MachinePasswordDialogListener() {
                    @Override
                    public void clickBtn(boolean matched_pw) {

                        //비밀번호가 일치했을 경우
                        if (matched_pw) {

                            //mac이 있을 경우
                            if (!TextUtils.isEmpty(items.get(position).getMcIotMac()) && items.get(position).getMcIotMac() != null) {

                                String del_flag;

                                if (holder.sw.isChecked()) {
                                    del_flag = "MM";
                                    holder.machine_stateTV.setText("[가동중]");
                                    holder.machine_remain_timeTV.setText(Common.getInstance().isNullToZero(items.get(position).getMcRunningtime()) + "시간 사용중");
                                    holder.sw.setChecked(true);
                                    items.get(position).setSelected(true);
                                    holder.graphLL.setVisibility(View.VISIBLE);
                                    Glide.with(context).load(R.drawable.icon_state2).into(holder.machine_stateIV);

                                } else {
                                    del_flag = "STOP";
                                    holder.machine_stateTV.setText("[가동중지]");
                                    holder.machine_remain_timeTV.setText("소모품 교환까지 " + Common.getInstance().isNullToZero(items.get(position).getMcRunningtime()) + "시간 남음");
                                    holder.sw.setChecked(false);
                                    items.get(position).setSelected(false);
//                                    holder.graphLL.setVisibility(View.GONE);
                                    holder.graphLL.setVisibility(View.VISIBLE);
                                    holder.machine_stateIV.setImageResource(R.drawable.icon_stop);

                                }

                                Bundle bundle = new Bundle();
                                bundle.putString("mc_idx", items.get(position).getMcIdx());
                                bundle.putString("mac", items.get(position).getMcIotMac());
                                bundle.putString("del_flag", del_flag);

                                clickListener.clickBtn(bundle);
                            }

                        } else {

                            holder.sw.toggle();

                            if (!holder.sw.isChecked()) {
                                holder.machine_stateTV.setText("[가동중지]");
                                holder.machine_remain_timeTV.setText("소모품 교환까지 " + Common.getInstance().isNullToZero(items.get(position).getMcRunningtime()) + "시간 남음");
                                items.get(position).setSelected(false);
                                holder.graphLL.setVisibility(View.VISIBLE);
                                holder.machine_stateIV.setImageResource(R.drawable.icon_stop);

                            } else {
                                holder.machine_stateTV.setText("[가동중]");
                                holder.machine_remain_timeTV.setText(Common.getInstance().isNullToZero(items.get(position).getMcRunningtime()) + "시간 사용중");
                                items.get(position).setSelected(true);
                                holder.graphLL.setVisibility(View.VISIBLE);
                                Glide.with(context).load(R.drawable.icon_state2).into(holder.machine_stateIV);
                            }
//                            MyApplication.doing_toggle = false;
                        }
                    }
                });
                dialog.show();
            }
        });

        //옵션 버튼 클릭 리스너
        holder.time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle bundle = new Bundle();
                bundle.putString("mc_idx", items.get(position).getMcIdx());
                bundle.putString("pt_idx", pt_idx);
                bundle.putString("cp_idx", cp_idx);

                timeClickListener.clickBtn(bundle);
            }
        });

        //차트 터치 리스너 >> EnterpriseRecyclerAdapter로 전달되어 상세페이지 팝업을 띄운다
        View.OnTouchListener touch = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_UP) {

                    if (v == holder.temperaturePC1) {
                        pop_type = "temperatureNtc";
                    } else if (v == holder.temperaturePC2) {
                        pop_type = "temperaturePt";
                    } else if (v == holder.pressurePC1) {
                        pop_type = "pressure1";
                    } else if (v == holder.pressurePC2) {
                        pop_type = "pressure2";
                    } else if (v == holder.pressurePC3) {
                        pop_type = "pressure3";
                    }

                    Bundle bundle = new Bundle();
                    bundle.putString("mc_idx", items.get(position).getMcIdx());
                    bundle.putString("pt_idx", pt_idx);
                    bundle.putString("cp_idx", cp_idx);
                    bundle.putString("mac", items.get(position).getMcIotMac());
                    bundle.putString("chart_type", pop_type);

                    chartClickListener.clickBtn(bundle);
                    return true;

                } else {
                    return false;
                }
            }
        };

        //차트 터치 리스너와 동일 동작을 한다
        View.OnClickListener click = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (v == holder.currentLL1) {
                    pop_type = "current1";
                } else if (v == holder.currentLL2) {
                    pop_type = "current2";
                } else if (v == holder.currentLL3) {
                    pop_type = "current3";
                }

                Bundle bundle = new Bundle();
                bundle.putString("mc_idx", items.get(position).getMcIdx());
                bundle.putString("pt_idx", pt_idx);
                bundle.putString("cp_idx", cp_idx);
                bundle.putString("mac", items.get(position).getMcIotMac());
                bundle.putString("chart_type", pop_type);

                chartClickListener.clickBtn(bundle);
            }
        };

        holder.currentLL1.setOnClickListener(click);
        holder.currentLL2.setOnClickListener(click);
        holder.currentLL3.setOnClickListener(click);

        holder.pressurePC1.setOnTouchListener(touch);
        holder.pressurePC2.setOnTouchListener(touch);
        holder.pressurePC3.setOnTouchListener(touch);
        holder.temperaturePC1.setOnTouchListener(touch);
        holder.temperaturePC2.setOnTouchListener(touch);
    }


    @Override
    public int getItemCount() {
        return items.size();
    }

    void addItem(ArrayList<MachineItem> data) {
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void clearItem() {
        items.clear();
        notifyDataSetChanged();
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {

        TextView seq, name, spec;
        //Switch sw;
        ToggleButton sw;
        LinearLayout progressFrame;
        RelativeLayout time;
        ProgressBar progress;
        TextView min, max, qr;

//        String pt_idx, cp_idx, mc_idx;

        int viewWidth;
        String temp_time;

        LinearLayout graphLL;
        BarChart currentBC1, currentBC2, currentBC3;
        PieChart pressurePC1, pressurePC2, pressurePC3, temperaturePC1, temperaturePC2;
        TextView temperature_maxTV1, temperature_maxTV2, current_valueTV1, current_valueTV2, current_valueTV3;
        LinearLayout currentLL1, currentLL2, currentLL3;

        LinearLayout enterprise_prodLL, enterprise_prod_playLL, time_marginLL;
        TextView enterprise_prod_machine_stopTV, machine_stateTV, machine_remain_timeTV, temperature_titleTV, enterprise_prod_playTV;
        ImageView machine_stateIV, enterprise_prod_playIV;

        ItemViewHolder(View itemView) {
            super(itemView);
            seq = itemView.findViewById(R.id.seq);
            name = itemView.findViewById(R.id.name);
            spec = itemView.findViewById(R.id.spec);
            qr = itemView.findViewById(R.id.qr);
            time = itemView.findViewById(R.id.time);
            sw = itemView.findViewById(R.id.sw);
            progressFrame = itemView.findViewById(R.id.progressFrame);
            progress = itemView.findViewById(R.id.progress);
            min = itemView.findViewById(R.id.min);
            max = itemView.findViewById(R.id.max);
//            lastDt = itemView.findViewById(R.id.lastDt);

            graphLL = itemView.findViewById(R.id.graphLL);
            currentBC1 = itemView.findViewById(R.id.currentBC1);
            currentBC2 = itemView.findViewById(R.id.currentBC2);
            currentBC3 = itemView.findViewById(R.id.currentBC3);
            pressurePC1 = itemView.findViewById(R.id.pressurePC1);
            pressurePC2 = itemView.findViewById(R.id.pressurePC2);
            pressurePC3 = itemView.findViewById(R.id.pressurePC3);
            temperaturePC1 = itemView.findViewById(R.id.temperaturePC1);
            temperaturePC2 = itemView.findViewById(R.id.temperaturePC2);
            temperature_maxTV1 = itemView.findViewById(R.id.temperature_maxTV1);
            temperature_maxTV2 = itemView.findViewById(R.id.temperature_maxTV2);
            current_valueTV1 = itemView.findViewById(R.id.current_valueTV1);
            current_valueTV2 = itemView.findViewById(R.id.current_valueTV2);
            current_valueTV3 = itemView.findViewById(R.id.current_valueTV3);
            currentLL1 = itemView.findViewById(R.id.currentLL1);
            currentLL2 = itemView.findViewById(R.id.currentLL2);
            currentLL3 = itemView.findViewById(R.id.currentLL3);

            enterprise_prodLL = itemView.findViewById(R.id.enterprise_prodLL);
            enterprise_prod_machine_stopTV = itemView.findViewById(R.id.enterprise_prod_machine_stopTV);
            machine_stateTV = itemView.findViewById(R.id.machine_stateTV);
            machine_remain_timeTV = itemView.findViewById(R.id.machine_remain_timeTV);

            machine_stateIV = itemView.findViewById(R.id.machine_stateIV);

            enterprise_prod_playIV = itemView.findViewById(R.id.enterprise_prod_playIV);
            enterprise_prod_playTV = itemView.findViewById(R.id.enterprise_prod_playTV);
            enterprise_prod_playLL = itemView.findViewById(R.id.enterprise_prod_playLL);

            time_marginLL = itemView.findViewById(R.id.time_marginLL);

        }

        void onBind(MachineItem data) {

            if (data.getMonitoring() != null) {
                monitoringArray = data.getMonitoring();

            } else {
                monitoringArray = null;
            }

            // LIVE 버튼 초기세팅
            if(!data.isRunning()){
                enterprise_prod_playIV.setImageResource(R.drawable.icon_play_gray);
                enterprise_prod_playTV.setTextColor(itemView.getResources().getColor(R.color.gray));
                enterprise_prod_playLL.setBackgroundResource(R.drawable.border_gray_fill_white_round_30_stroke_2);

            } else {
                enterprise_prod_playLL.setBackgroundResource(R.drawable.border_blue_fill_white_round_30_stroke_2);
                enterprise_prod_playIV.setImageResource(R.drawable.icon_play_blue);
                enterprise_prod_playTV.setTextColor(context.getResources().getColor(R.color.light_blue));
            }

            get_MonitoringArray();
//
//            if (!MyApplication.stop_ui_change) {
//                get_MonitoringArray();
//            }

            if (data.getMcIotMac() != null) {
                sw.setVisibility(View.VISIBLE);
                mac = data.getMcIotMac();

                enterprise_prod_playLL.setVisibility(View.VISIBLE);
                time_marginLL.setVisibility(View.GONE);
                progressFrame.setVisibility(View.VISIBLE);
                enterprise_prod_machine_stopTV.setVisibility(View.GONE);

                if (data.getDelFlag().equals("MM")) {

                    machine_stateTV.setText("[가동중]");
                    graphLL.setVisibility(View.VISIBLE);
                    Glide.with(context).load(R.drawable.icon_state2).into(machine_stateIV);
                    machine_remain_timeTV.setText(Common.getInstance().isNullToZero(data.getMcRunningtime()) + "시간 사용중");


                } else {
                    machine_stateTV.setText("[가동중지]");
//                    graphLL.setVisibility(View.GONE);
                    graphLL.setVisibility(View.VISIBLE);
                    machine_stateIV.setImageResource(R.drawable.icon_stop);
                    machine_remain_timeTV.setText("소모품 교환까지 " + Common.getInstance().isNullToZero(data.getMcRunningtime()) + "시간 남음");

                }

            } else {
                enterprise_prod_playLL.setVisibility(View.GONE);
                progressFrame.setVisibility(View.GONE);
                graphLL.setVisibility(View.GONE);
                time_marginLL.setVisibility(View.VISIBLE);
                sw.setVisibility(View.GONE);
                enterprise_prod_machine_stopTV.setText("IoT가 설치되지 않았습니다.");
                enterprise_prod_machine_stopTV.setVisibility(View.VISIBLE);
            }

            name.setText(data.getProductData().getPdTtypeStr());
            spec.setText(data.getProductData().getPdName());

//            lastDt.setText("교환정보 없음");

//            if (data.getMcExchangedt().toString().equals("")){
//                lastDt.setText("교환정보 없음");
//            }else{
//                lastDt.setText(data.getMcExchangedt().toString());
//            }

            if (data.getQrCode() != null) {
//                qr.setText("[없음]");
//            } else {
                qr.setText("[" + data.getQrCode().toString() + "]");
            }

            sw.setOnCheckedChangeListener(null);

            if (data.getDelFlag().equals("MM")) {
                data.setSelected(true);

            } else {
                data.setSelected(false);
            }

            sw.setChecked(data.isSelected());

            sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    data.setSelected(isChecked);

                    if (isChecked) {
                        data.setDelFlag("MM");
                        graphLL.setVisibility(View.VISIBLE);
                        Glide.with(context).load(R.drawable.icon_state2).into(machine_stateIV);
//                        machine_stateTV.setText("가동중");
//                        machine_remain_timeTV.setText(Common.getInstance().isNullToZero(data.getMcRunningtime()) + "시간 사용중");

                        data.setSelected(true);
                    } else {
                        data.setDelFlag("STOP");
//                        graphLL.setVisibility(View.GONE);
                        graphLL.setVisibility(View.VISIBLE);
                        machine_stateIV.setImageResource(R.drawable.icon_stop);
//                        machine_stateTV.setText("[가동중지]");
//                        machine_remain_timeTV.setText("소모품 교환까지 " + Common.getInstance().isNullToZero(data.getMcRunningtime()) + "시간 남음");
                        data.setSelected(false);
                    }
                }
            });

            int runningTime = Integer.parseInt(Common.getInstance().isNullToZero(data.getMcRunningtime()));
            runningTime = 998;
            int cycle = Integer.parseInt(Common.getInstance().isNullToZero(data.getMcCycle()));
            cycle = 2000;
            double per;
            if (cycle == 0 && runningTime != 0) {
                per = 100;
            } else {
                per = ((double) runningTime / (double) cycle) * 100;
            }
            //Log.d("1234", "per = " + per + "/runningTime = " + runningTime + "/cycle = " + cycle);
            //progress.setMin(runningTime);
            progress.setMax(100);
            progress.setProgress((int) per);

            min.setText(runningTime + "");
            max.setText(cycle + "");
            //Log.d("1234", progress.getMax() + "");

            /*if (data.getSubIdx1() == null){
                progressFrame.setVisibility(View.GONE);
            } else *//*if (data.getMcCycle().equals("0")){
                progressFrame.setVisibility(View.GONE);
            } else{
            }*/

            pt_idx = data.getPtIdx();
            cp_idx = data.getCpIdx();
//            mc_idx = data.getMcIdx();

        }

        public void get_MonitoringArray() {

            MonitoringData monitoringData = null;

            if (monitoringArray != null) {
                monitoringData = monitoringArray.get(0);

            } else {
                monitoringData = new MonitoringData("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", mac);
            }

            //전류차트
            if (monitoringData.getCurrent1() != null && !monitoringData.getCurrent1().equals("0")) {

                current = Float.parseFloat(monitoringData.getCurrent1());
                current_max = monitoringData.getCurrent1Max();

                if (current_max.equals("0") || Float.parseFloat(current_max) < 1) {
                    current_max = "75";
                }
                setBarChart(currentBC1, Common.getInstance().valueConvert(current + ""), current_max, current_valueTV1);

            } else {
                setBarChart(currentBC1, "0", "75", current_valueTV1);
            }

            if (monitoringData.getCurrent2() != null && !monitoringData.getCurrent2().equals("0")) {

                current = Float.parseFloat(monitoringData.getCurrent2());
                current_max = monitoringData.getCurrent2Max();

                if (current_max.equals("0") || Float.parseFloat(current_max) < 1) {
                    current_max = "75";
                }
                setBarChart(currentBC2, Common.getInstance().valueConvert(current + ""), current_max, current_valueTV2);

            } else {
                setBarChart(currentBC2, "0", "75", current_valueTV2);
            }

            if (monitoringData.getCurrent3() != null && !monitoringData.getCurrent3().equals("0")) {

                current = Float.parseFloat(monitoringData.getCurrent3());
                current_max = monitoringData.getCurrent3Max();

                if (current_max.equals("0") || Float.parseFloat(current_max) < 1) {
                    current_max = "75";
                }
                setBarChart(currentBC3, Common.getInstance().valueConvert(current + ""), current_max, current_valueTV3);

            } else {
                setBarChart(currentBC3, "0", "75", current_valueTV3);
            }

            String temp_temperature;

            if (monitoringData.getTempNtc() != null && !monitoringData.getTempNtc().equals("0")) {

                temp_temperature = Common.getInstance().valueConvert(monitoringData.getTempNtc());
                temperature = temp_temperature;
                temperature_max = Common.getInstance().valueConvert(monitoringData.getTempNtcMax());

                if (temperature_max.equals("0") || Float.parseFloat(temperature_max) < 1) {
                    temperature_max = "120";
                }
                temperature_maxTV1.setText(temperature_max);
                setPieChart(temperature, Float.parseFloat(temperature_max), temperaturePC1);

            } else {
                setPieChart("0", 120, temperaturePC1);
            }

            if (monitoringData.getTempPt100() != null && !monitoringData.getTempPt100().equals("0")) {

                temp_temperature = Common.getInstance().valueConvert(monitoringData.getTempPt100());
                temperature = temp_temperature;
                temperature_max = Common.getInstance().valueConvert(monitoringData.getTempPt100Max());

                if (temperature_max.equals("0") || Float.parseFloat(temperature_max) < 1) {
                    temperature_max = "120";
                }
                temperature_maxTV2.setText(temperature_max);
                setPieChart(temperature, Float.parseFloat(temperature_max), temperaturePC2);

            } else {
                setPieChart("0", 120, temperaturePC2);
            }

            String temp_pressure;

            if (monitoringData.getPressure1() != null && !monitoringData.getPressure1().equals("0")) {

                temp_pressure = Common.getInstance().valueConvert1(monitoringData.getPressure1());
                pressure = temp_pressure;
                pressure_max = monitoringData.getPressure1Max();

                if (pressure_max.equals("0") || Float.parseFloat(pressure_max) < 1) {
                    pressure_max = "10";
                }

                setPieChart(pressure, Float.parseFloat(pressure_max), pressurePC1);

            } else {
                setPieChart("0", 10, pressurePC1);
            }

            if (monitoringData.getPressure2() != null && !monitoringData.getPressure2().equals("0")) {

                temp_pressure = Common.getInstance().valueConvert1(monitoringData.getPressure2());
                pressure = temp_pressure;
                pressure_max = monitoringData.getPressure2Max();

                if (pressure_max.equals("0") || Float.parseFloat(pressure_max) < 1) {
                    pressure_max = "10";
                }
                setPieChart(pressure, Float.parseFloat(pressure_max), pressurePC2);

            } else {
                setPieChart("0", 10, pressurePC2);
            }

            if (monitoringData.getPressure3() != null && !monitoringData.getPressure3().equals("0")) {

                temp_pressure = Common.getInstance().valueConvert1(monitoringData.getPressure3());
                pressure = temp_pressure;
                pressure_max = monitoringData.getPressure3Max();

                if (pressure_max.equals("0") || Float.parseFloat(pressure_max) < 1) {
                    pressure_max = "10";
                }
                setPieChart(pressure, Float.parseFloat(pressure_max), pressurePC3);

            } else {
                setPieChart("0", 10, pressurePC3);
            }
        }
    }

    private void setBarChart(BarChart barChart, String value, String max, TextView textView) {

        String content = value + "A";
        SpannableString spannableString = new SpannableString(content);

        String word = "A";
        int start = content.indexOf(word);
        int end = start + word.length();

        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#000000")), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new RelativeSizeSpan(0.8f), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

        textView.setText(spannableString);

        //값이 한계치를 넘으면 한계치로 값을 재설정함
        if (Float.parseFloat(value) >= Float.parseFloat(max)) {
            value = max;
        }

        ArrayList<BarEntry> bar_entries = new ArrayList<>();

        if (TextUtils.isEmpty(value)) {
            barChart.setNoDataText("데이터 없음");
            barChart.invalidate();
        } else {

            bar_entries.add(new BarEntry(0, Integer.parseInt(value)));
        }

        BarDataSet dataSet = new BarDataSet(bar_entries, ""); // 변수로 받아서 넣어줘도 됨
        dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
        //경고
        if (Float.parseFloat(value) >= Float.parseFloat(max)) {
            dataSet.setColor(ContextCompat.getColor(context, R.color.red));
            //주의
        } else if (Float.parseFloat(value) >= Float.parseFloat(max) * 0.85) {
            dataSet.setColor(ContextCompat.getColor(context, R.color.dark_yellow));
            barChart.setRenderer(new RoundedBarChart(barChart, barChart.getAnimator(), barChart.getViewPortHandler()));
            //정상
        } else {
//            dataSet.setColor(ContextCompat.getColor(context, R.color.light_green));
            dataSet.setColor(ContextCompat.getColor(context, R.color.bar_chart_green));
            barChart.setRenderer(new RoundedBarChart(barChart, barChart.getAnimator(), barChart.getViewPortHandler()));
        }

        dataSet.setBarShadowColor(Color.parseColor("#EAEAEA"));
        dataSet.setDrawValues(false);

        BarData data = new BarData(dataSet);
        data.setBarWidth(0.55f);

        barChart.setDrawBarShadow(true); // 그래프 그림자
        barChart.setTouchEnabled(false); // 차트 터치 막기
        barChart.setDrawValueAboveBar(true); // 입력?값이 차트 위or아래에 그려질 건지 (true=위, false=아래)
        barChart.setPinchZoom(false); // 두손가락으로 줌 설정
        barChart.setDrawGridBackground(false); // 격자구조
        barChart.setDescription(null); // 그래프 오른쪽 하단에 라벨 표시
        barChart.getLegend().setEnabled(false); // 차트 범례 설정(legend object chart)
        barChart.setExtraOffsets(5, -50, 0, -50);
        barChart.setNoDataText("데이터 없음");

        //x축
        XAxis xAxis = barChart.getXAxis();
        xAxis.setEnabled(false);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        //y축
        YAxis yAxisL = barChart.getAxisLeft();
        YAxis yAxisR = barChart.getAxisRight();
        yAxisL.setDrawAxisLine(false);
        yAxisL.setDrawLabels(false);
        yAxisL.setDrawGridLines(false);
        yAxisR.setDrawGridLines(false);
        yAxisR.setDrawAxisLine(false);
        yAxisR.setDrawLabels(true);
        yAxisR.setLabelCount(2, true);
        yAxisR.setXOffset(-10f);
        yAxisR.setAxisMaximum(Float.parseFloat(max));
        yAxisR.setAxisMinimum(0);

        barChart.setData(data);
        barChart.invalidate();
    }

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

        lineChart.clear();
        entries.clear();
        String line_color = "#82bb6b";

        Integer[] number_sort = new Integer[number.size()];

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

            String value = Common.getInstance().valueConvert(number.get(i));
            entries.add(new Entry(i, Integer.parseInt(value)));
            number_sort[i] = Integer.parseInt(value);
        }

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

        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSet.setCubicIntensity(0.2f);
        lineDataSet.setDrawFilled(true);

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

            if (Integer.parseInt(Common.getInstance().valueConvert(number.get(i))) > Float.parseFloat(current_max)) {
                line_color = "#CC2828";
                lineDataSet.setFillColor(Color.parseColor("#CC2828"));
                break;

            } else if (Integer.parseInt(Common.getInstance().valueConvert(number.get(i))) > Float.parseFloat(current_max) * 0.85) {
                lineDataSet.setFillColor(Color.parseColor("#FFC300"));
                break;

            } else {
                lineDataSet.setFillColor(Color.parseColor("#e9ffe0"));
                break;
            }
        }

        lineDataSet.setCircleColor(Color.parseColor("#368dd2"));
        lineDataSet.setColor(Color.parseColor(line_color));
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawHorizontalHighlightIndicator(false);
        lineDataSet.setDrawHighlightIndicators(false);
        lineDataSet.setDrawValues(false);

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

        XAxis xAxis = lineChart.getXAxis();
        ValueFormatter xAxisFormatter = new TimeAxisValueFormatter(lineChart);

        xAxis.setGranularityEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setGridDashedLine(new DashPathEffect(new float[]{3, 3}, 0));
        xAxis.setLabelCount(3, true);
        xAxis.setValueFormatter(xAxisFormatter);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setGranularity(0f);

        Arrays.sort(number_sort);

        YAxis yLAxis = lineChart.getAxisLeft();
        yLAxis.setTextColor(Color.BLACK);
        yLAxis.setAxisMaximum(number_sort[number_sort.length - 1] + 5f);
        yLAxis.setAxisMinimum(number_sort[0] - 5f);
        yLAxis.setDrawAxisLine(false);
        yLAxis.setDrawGridLines(false);
        yLAxis.setAxisLineColor(Color.BLACK);
        yLAxis.setLabelCount(5, true);

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

        lineChart.setVisibleXRange(305, 305);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getLegend().setEnabled(false);
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setDrawGridBackground(false);
        lineChart.setScaleXEnabled(false);
        lineChart.setScaleYEnabled(false);

        lineChart.setDescription(null);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.setTouchEnabled(true);
        lineChart.invalidate();

    }

    public class TimeAxisValueFormatter extends ValueFormatter {

        TimeAxisValueFormatter(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {

            String set_time;
            int half = time_list.size() / 2;
            int last = time_list.size() - 1;
            int match = (int) value;

            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 {
                set_time = "";
            }

            return set_time;
        }
    }

    private void setPieChart(String number, float max, PieChart pieChart) {

        PieDataSet dataSet;

        ArrayList<PieEntry> values = new ArrayList<>();

        if (pieChart.getId() == R.id.temperaturePC1 || pieChart.getId() == R.id.temperaturePC2) {

            pieChart.setMaxAngle(180f);
            pieChart.setRotationAngle(180f);
            pieChart.setTransparentCircleRadius(70f);
            pieChart.setHoleRadius(65f);
            pieChart.setExtraOffsets(10f, -50f, 10f, -90f);
            pieChart.setCenterTextOffset(0, -10);
            pieChart.setCenterTextSize(25f);

            int count = 0;

            if (Integer.parseInt(number) > 0) {
                count = Integer.parseInt(Common.getInstance().valueConvert(number));
            }

            if (count >= max) count = (int) max;

            values.add(new PieEntry(count, (Drawable) null));
            values.add(new PieEntry(max - count, (Drawable) null));

            dataSet = new PieDataSet(values, "");

            //경고
            if (count >= max) {
                dataSet.setColors(Color.parseColor("#CC2828"), Color.parseColor("#EAEAEA"));

                //주의
            } else if (count >= max - 20) {
                dataSet.setColors(Color.parseColor("#FFC300"), Color.parseColor("#EAEAEA"));

                //정상
            } else {
//                dataSet.setColors(Color.parseColor("#368dd2"), Color.parseColor("#EAEAEA"));
                dataSet.setColors(Color.parseColor("#0075BF"), Color.parseColor("#EAEAEA"));
            }

            String content = number + "℃";
            SpannableString spannableString = new SpannableString(content);

            String word = "℃";
            int start = content.indexOf(word);
            int end = start + word.length();

            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#000000")), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new RelativeSizeSpan(0.7f), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

            pieChart.setCenterText(spannableString);

        } else {

//            pieChart.setTransparentCircleRadius(83f);
            pieChart.setHoleRadius(80f);
            pieChart.setCenterTextSize(27f);

            float count = Float.parseFloat(Common.getInstance().valueConvert1(number));

            if (count >= max) count = max;

            values.add(new PieEntry(count, (Drawable) null));
            values.add(new PieEntry(max - count, (Drawable) null));

            dataSet = new PieDataSet(values, "");

            if (count >= max) {
                dataSet.setColors(Color.parseColor("#CC2828"), Color.parseColor("#EAEAEA"));

            } else if (count >= max - 1) {
                dataSet.setColors(Color.parseColor("#FFC300"), Color.parseColor("#EAEAEA"));

            } else {
//                dataSet.setColors(Color.parseColor("#49a6a6"), Color.parseColor("#EAEAEA"));
                dataSet.setColors(Color.parseColor("#0075BF"), Color.parseColor("#EAEAEA"));

            }

            String content = number + "Bar\nMAX " + max;
            SpannableString spannableString = new SpannableString(content);

            String word = "Bar";
            int start = content.indexOf(word);
            int end = content.length();

//            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#666666")), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new RelativeSizeSpan(0.3f), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

            pieChart.setCenterText(spannableString);

        }

        dataSet.setSliceSpace(1);
        dataSet.setSelectionShift(0f);

        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.WHITE);
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setRotationEnabled(false);
        pieChart.setDrawCenterText(true);
        pieChart.setNoDataText("데이터 없음");

        pieChart.setCenterTextColor(Color.BLACK);
        pieChart.setEntryLabelColor(Color.WHITE);
        pieChart.getLegend().setEnabled(false);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setDrawValues(false);

        pieChart.setData(data);
        pieChart.invalidate();

    }
}
