package com.cygnusa.hyperm.fragments;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import com.budiyev.android.circularprogressbar.CircularProgressBar;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
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.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.cygnusa.hyperm.AMHomeActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.autofit.AutofitTextView;
import com.cygnusa.hyperm.slider.Animations.DescriptionAnimation;
import com.cygnusa.hyperm.slider.Indicators.PagerIndicator;
import com.cygnusa.hyperm.slider.SliderLayout;
import com.cygnusa.hyperm.slider.SliderTypes.BaseSliderView;
import com.cygnusa.hyperm.slider.SliderTypes.DefaultSliderView;
import com.cygnusa.hyperm.slider.Tricks.ViewPagerEx;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.ManagerDashBoardResponse;
import com.cygnusa.hyperm.wrappers.ZoneResponse;

import java.text.DecimalFormat;
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.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class AMHomeFragment extends Fragment implements BaseSliderView.OnSliderClickListener,
        ViewPagerEx.OnPageChangeListener, OnChartValueSelectedListener {

    public static Handler.Callback callback;
    View mainView;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    ManagerDashBoardResponse data = new ManagerDashBoardResponse();
    private ZoneResponse RM_DATA = new ZoneResponse();
    private ZoneResponse ZM_DATA = new ZoneResponse();
    private ZoneResponse AM_DATA = new ZoneResponse();
    private CircularProgressBar progressBar;
    private NumberPicker datePicker;
    private AutofitTextView mPrgressText;
    private ArrayList<String> MONTH_YEAR;
    private Handler PICKER_HANDLER = new Handler();
    private SliderLayout mDemoSlider;
    private LinearLayout menuLayout;
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;
    private BarChart mChart;
    private TextView txtUserTotal;
    private PieChart mPieChart;
    private LinearLayout linearRegion;
    private LinearLayout linearArea;
    private Spinner spinZone, spinRegion, spinArea;
    private ArrayList<String> regionList;
    private ArrayList<String> zoneList;
    private Calendar calendar;
    private ArrayList<String> areaList;
    public static int yearValue, monthValue;

    public AMHomeFragment() {

    }

    public void onResumeFragment() {

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_am_home, container, false);
        datePicker = v.findViewById(R.id.extendedDate);
        return v;
    }

    private RectF mOnValueSelectedRectF = new RectF();


    @SuppressLint("CheckResult")
    private void setBannerSlider() {
        mDemoSlider.removeAllSliders();
        RequestOptions requestOptions = new RequestOptions();
        requestOptions
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.placeholder);

        for (int i = 0; i < GlobalData.BANNERS.size(); i++) {
            DefaultSliderView sliderView = new DefaultSliderView(getActivity());
            sliderView
                    .image(GlobalData.BANNERS.get(i).getImage().trim())
                    .setRequestOption(requestOptions)
                    .setBackgroundColor(Color.TRANSPARENT)
                    .setProgressBarVisible(true)
                    .setOnSliderClickListener(this);

            sliderView.bundle(new Bundle());
            mDemoSlider.addSlider(sliderView);
        }


    }

    private ArrayList<String> generateMonthAndYear() {
        ArrayList<String> yearList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        yearValue = currentYear;
        monthValue = currentMonth;
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat format1 = new SimpleDateFormat("MMM yyyy");

        for (int i = currentYear; i > currentYear - 10; i--) {
            if (i == currentYear) {
                for (int j = currentMonth; j > 0; j--) {
                    try {
                        Date date = format.parse("01-" + (j < 10 ? "0" : "") + j + "-" + i);
                        yearList.add(0, format1.format(date));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                for (int j = 12; j > 0; j--) {
                    try {
                        Date date = format.parse("01-" + (j < 10 ? "0" : "") + j + "-" + i);
                        yearList.add(0, format1.format(date));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return yearList;
    }

    private void getAMDashBoard(int year, int month, String zmemail, String rmemail, String amemail) {

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("14")) {
            amemail = "all";
            rmemail = "all";
            zmemail = "all";
            GlobalData.amEmail = "all";
            GlobalData.rmEmail = "all";
            GlobalData.zmEmail = "all";
        }

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
            zmemail = "all";
            GlobalData.zmEmail = "all";
        }

        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("zmemail", zmemail);
                map.put("rmemail", rmemail);
                map.put("amemail", amemail);
                restService.getAreaManagerDashboard(year, month, map).enqueue(new Callback<ManagerDashBoardResponse>() {
                    @Override
                    public void onResponse(Call<ManagerDashBoardResponse> call, Response<ManagerDashBoardResponse> response) {
                        data = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (data != null && data.getStatus() == 200) {
                            setDashboardData();
                            if (data.getData().getLearning().getUser_total() != null)
                                txtUserTotal.setText(String.format("Total DSE : %s", data.getData().getLearning().getUser_total()));
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ManagerDashBoardResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setAssessmentData() {
        mPieChart.getDescription().setEnabled(false);
        mPieChart.getLegend().setEnabled(false);
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        mPieChart.setExtraOffsets(5, 10, 5, 5);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);
        ArrayList<PieEntry> entries = new ArrayList<>();
        String[] pieLegend = {"Active", "Expired", "Published"};
        float[] floats = {0, 0, 0};
        try {
            floats = new float[]{Float.parseFloat(data.getData().getAssessment().getActive()),
                    Float.parseFloat(data.getData().getAssessment().getExpired()),
                    Float.parseFloat(data.getData().getAssessment().getPublished())};
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 3; i++) {
            entries.add(new PieEntry(floats[i], pieLegend[i], pieLegend[i]));
        }

        PieDataSet dataSet = new PieDataSet(entries, "");

        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        dataSet.setValueLinePart1OffsetPercentage(0.7f);
        dataSet.setValueLinePart1Length(0.45f);
        dataSet.setValueLinePart2Length(0.7f);
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        PieData data = new PieData(dataSet);

        IValueFormatter formatter = new IValueFormatter() {

            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                DecimalFormat mFormat = new DecimalFormat("###,###,###,##0");
                return mFormat.format(value) + " " + entry.getData().toString();
            }
        };

        data.setValueFormatter(formatter);
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.highlightValues(null);
        mPieChart.setData(data);
        mPieChart.invalidate();
    }

    private void setDashboardData() {
        if (Float.parseFloat(data.getData().getSales().getTarget()) > 0) {
            progressBar.setMaximum(Float.parseFloat(data.getData().getSales().getTarget()));
            progressBar.setProgress(Float.parseFloat(data.getData().getSales().getAchieved()));
        } else {
            progressBar.setMaximum(1);
            progressBar.setProgress(0);
        }
        mPrgressText.setText(String.format("%s/%s", data.getData().getSales().getAchieved(), data.getData().getSales().getTarget()));
        setDSEData();
        setAssessmentData();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onSliderClick(BaseSliderView baseSliderView) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    public View getSlider() {
        return mDemoSlider;
    }

    public View getMenuLayout() {
        return menuLayout;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mViewCreated = false;
        mUserSeen = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!mUserSeen && isVisibleToUser) {
            mUserSeen = true;
            onViewCreatedFirstSight();
        }
    }


    @SuppressLint("StaticFieldLeak")
    private void onViewCreatedFirstSight() {
        if (mUserSeen && mViewCreated) {
            MONTH_YEAR = generateMonthAndYear();
            datePicker.setMinValue(0);
            datePicker.setMaxValue(MONTH_YEAR.size() - 1);
            datePicker.setDisplayedValues(MONTH_YEAR.toArray(new String[0]));
            datePicker.setValue(MONTH_YEAR.size() - 1);
            if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                getZMDetails();
            } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                    || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                getRMDetails(GlobalData.user.getData().getEmailid(), GlobalData.user.getData().getZone());
            } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
                getAMDetails(GlobalData.user.getData().getEmailid());
            } else {
                getAMDashBoard(yearValue, monthValue, "all", "all", GlobalData.user.getData().getEmailid());
            }

        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        ((MainApplication) Objects.requireNonNull(getActivity()).getApplication()).addAccessToken(String.format("Bearer %s", GlobalData.user.getAccess_token().trim()));
        restService = ((MainApplication) Objects.requireNonNull(getActivity()).getApplication()).getClient();
        mDemoSlider = mainView.findViewById(R.id.slider);
        mPrgressText = mainView.findViewById(R.id.progressText);
        LinearLayout targetLayout = mainView.findViewById(R.id.targetSalesLayout);
        menuLayout = mainView.findViewById(R.id.menuLayout);
        progressBar = mainView.findViewById(R.id.progress_bar);

        mPrgressText = mainView.findViewById(R.id.progressText);
        txtUserTotal = mainView.findViewById(R.id.txt_total_dse);
        View piechartView = mainView.findViewById(R.id.piechartView);
        View barchartView2 = mainView.findViewById(R.id.barchartView);
        linearRegion = mainView.findViewById(R.id.LinearRegion);
        LinearLayout linearZone = mainView.findViewById(R.id.LinearZone);
        spinZone = mainView.findViewById(R.id.spinZone);
        linearArea = mainView.findViewById(R.id.LinearArea);
        CardView hoRankingCard = mainView.findViewById(R.id.hoRankingCard);
        CardView amRankingCard = mainView.findViewById(R.id.amRankingCard);
        LinearLayout hoRanking = mainView.findViewById(R.id.hoRanking);

        spinRegion = mainView.findViewById(R.id.spinRegion);
        spinArea = mainView.findViewById(R.id.spinArea);
        regionList = new ArrayList<>();
        zoneList = new ArrayList<>();
        calendar = Calendar.getInstance();
        areaList = new ArrayList<>();

        linearArea.setVisibility(View.GONE);
        linearRegion.setVisibility(View.GONE);
        linearZone.setVisibility(View.GONE);
        hoRankingCard.setVisibility(View.GONE);
        amRankingCard.setVisibility(View.GONE);

        if (GlobalData.user.getData().getRole().trim().equalsIgnoreCase("3")
                || GlobalData.user.getData().getRole().trim().equalsIgnoreCase("14")) {
            hoRankingCard.setVisibility(View.VISIBLE);
        } else {
            amRankingCard.setVisibility(View.VISIBLE);
        }

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
            linearRegion.setVisibility(View.VISIBLE);
            linearArea.setVisibility(View.VISIBLE);
        } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
            linearArea.setVisibility(View.VISIBLE);
        } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
            linearZone.setVisibility(View.VISIBLE);
            linearRegion.setVisibility(View.VISIBLE);
            linearArea.setVisibility(View.VISIBLE);
        }

        LinearLayout salesView = mainView.findViewById(R.id.salesView);
        LinearLayout assessmentView = mainView.findViewById(R.id.assessmentView);

        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                setBannerSlider();
                return false;
            }
        };

        targetLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler(AMHomeActivity.homeFragmentCallback).sendEmptyMessage(1);
            }
        });

        piechartView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler(AMHomeActivity.homeFragmentCallback).sendEmptyMessage(3);
            }
        });

        barchartView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler(AMHomeActivity.homeFragmentCallback).sendEmptyMessage(2);
            }
        });

        salesView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler(AMHomeActivity.homeFragmentCallback).sendEmptyMessage(5);
            }
        });

        assessmentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler(AMHomeActivity.homeFragmentCallback).sendEmptyMessage(6);
            }
        });

        hoRanking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler(AMHomeActivity.homeFragmentCallback).sendEmptyMessage(6);
            }
        });


        mChart = mainView.findViewById(R.id.barChart);
        mPieChart = mainView.findViewById(R.id.pieChart);

        mViewCreated = true;
        onViewCreatedFirstSight();
        datePicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        datePicker.setWrapSelectorWheel(false);
        datePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int oldvalue, final int newValue) {
                try {
                    PICKER_HANDLER.removeCallbacksAndMessages(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                PICKER_HANDLER.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        String[] str = MONTH_YEAR.get(newValue).trim().split(" ");
                        String month = str[0];
                        String year = str[1];
                        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
                        try {
                            Date date = dateFormat.parse("01-" + month + "-" + year);
                            calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            monthValue = calendar.get(Calendar.MONTH) + 1;
                            yearValue = calendar.get(Calendar.YEAR);

                            if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                                if (spinZone.getSelectedItemPosition() == 0) {
                                    getAMDashBoard(yearValue, monthValue, "all", "all", "all");
                                } else {
                                    if (spinRegion.getSelectedItemPosition() == 0) {
                                        getAMDashBoard(yearValue, monthValue,
                                                ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                                "all", "all");
                                    } else {
                                        if (spinArea.getSelectedItemPosition() == 0) {
                                            getAMDashBoard(yearValue, monthValue,
                                                    ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                                    RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                                    "all");
                                        } else {
                                            getAMDashBoard(yearValue, monthValue,
                                                    ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                                    RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                                    AM_DATA.getData().get(spinArea.getSelectedItemPosition() - 1).getEmail());
                                        }
                                    }
                                }
                            } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                                    || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                                if (spinRegion.getSelectedItemPosition() == 0) {
                                    getAMDashBoard(yearValue, monthValue, GlobalData.user.getData().getEmailid(), "all", "all");
                                } else {
                                    if (spinArea.getSelectedItemPosition() == 0) {
                                        getAMDashBoard(yearValue, monthValue, GlobalData.user.getData().getEmailid(),
                                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                                "all");
                                    } else {
                                        getAMDashBoard(yearValue, monthValue, GlobalData.user.getData().getEmailid(),
                                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                                AM_DATA.getData().get(spinArea.getSelectedItemPosition() - 1).getEmail());
                                    }
                                }
                            } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
                                if (spinArea.getSelectedItemPosition() == 0) {
                                    getAMDashBoard(yearValue, monthValue, "all", GlobalData.user.getData().getEmailid(), "all");
                                } else {
                                    getAMDashBoard(yearValue, monthValue, "all", GlobalData.user.getData().getEmailid(),
                                            AM_DATA.getData().get(spinArea.getSelectedItemPosition() - 1).getEmail());
                                }
                            } else {
                                getAMDashBoard(yearValue, monthValue, "all", "all", GlobalData.user.getData().getEmailid());
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }, 500);
            }
        });
        mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Default);
        PagerIndicator indicators = mainView.findViewById(R.id.custom_indicator);
        mDemoSlider.setCustomIndicator(indicators);
        mDemoSlider.setCustomAnimation(new DescriptionAnimation());
        mDemoSlider.setDuration(4000);
        mDemoSlider.addOnPageChangeListener(this);
    }

    private void getZMDetails() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                restService.getZone().enqueue(new Callback<ZoneResponse>() {
                    @Override
                    public void onResponse(Call<ZoneResponse> call, Response<ZoneResponse> response) {
                        ZM_DATA = response.body();

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (ZM_DATA != null && ZM_DATA.getStatus() == 200) {
                            zoneList.clear();
                            zoneList.add("All");
                            for (int i = 0; i < ZM_DATA.getData().size(); i++) {
                                zoneList.add(ZM_DATA.getData().get(i).getName());
                            }
                            setZMDetails();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ZoneResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                Log.e("iop", e.toString() + "");

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setZMDetails() {
        if (zoneList == null || zoneList.size() == 0) {
            return;
        }

        ArrayAdapter<String> zoneAdapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
                R.layout.spinner_region, zoneList);
        zoneAdapter.setDropDownViewResource(R.layout.spinner_region);
        spinZone.setAdapter(zoneAdapter);

        spinZone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    linearRegion.setVisibility(View.GONE);
                    linearArea.setVisibility(View.GONE);
                    getAMDashBoard(yearValue, monthValue, "all", "all", "all");
                    GlobalData.zmEmail = "all";
                    GlobalData.rmEmail = "all";
                    GlobalData.amEmail = "all";
                } else {
                    linearRegion.setVisibility(View.VISIBLE);
                    String email = ZM_DATA.getData().get(i - 1).getEmail();
                    GlobalData.zmEmail = email;
                    GlobalData.rmEmail = "all";
                    GlobalData.amEmail = "all";
                    String zone = ZM_DATA.getData().get(i - 1).getZone();
                    getRMDetails(email, zone);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spinZone.setSelection(0);
    }

    private void getRMDetails(String email, String zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("zone", email);
                map.put("zonename", zone);
                restService.getRegion(map).enqueue(new Callback<ZoneResponse>() {
                    @Override
                    public void onResponse(Call<ZoneResponse> call, Response<ZoneResponse> response) {
                        RM_DATA = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (RM_DATA != null && RM_DATA.getStatus() == 200) {
                            regionList.clear();
                            regionList.add("All");
                            for (int i = 0; i < RM_DATA.getData().size(); i++) {
                                regionList.add(RM_DATA.getData().get(i).getName());
                            }
                            setRMDetails();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ZoneResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setRMDetails() {
        if (regionList == null || regionList.size() == 0) {
            return;
        }

        ArrayAdapter<String> regionAdapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
                R.layout.spinner_region, regionList);
        regionAdapter.setDropDownViewResource(R.layout.spinner_region);
        spinRegion.setAdapter(regionAdapter);

        spinRegion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    linearArea.setVisibility(View.GONE);
                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getAMDashBoard(yearValue, monthValue,
                                ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                "all", "all");
                    } else {
                        getAMDashBoard(yearValue, monthValue, GlobalData.user.getData().getEmailid(), "all", "all");
                    }
                } else {
                    linearArea.setVisibility(View.VISIBLE);
                    String email = RM_DATA.getData().get(i - 1).getEmail();
                    GlobalData.rmEmail = email;
                    getAMDetails(email);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spinRegion.setSelection(0);
    }

    private void getAMDetails(String email) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("region", email);
                restService.getArea(map).enqueue(new Callback<ZoneResponse>() {
                    @Override
                    public void onResponse(Call<ZoneResponse> call, Response<ZoneResponse> response) {
                        AM_DATA = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (AM_DATA != null && AM_DATA.getStatus() == 200) {
                            setAMDetails();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ZoneResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }

    }

    private void setDSEData() {
        mChart.getLegend().setEnabled(false);
        mChart.getXAxis().setDrawGridLines(false);
        mChart.getAxisRight().setDrawLabels(false);
        mChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        mChart.getXAxis().setGranularity(1.0f);
        mChart.getAxisLeft().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value);
            }
        });

        mChart.getAxisLeft().setGranularity(1.0f);
        mChart.getDescription().setEnabled(false);

        IndexAxisValueFormatter vf = new IndexAxisValueFormatter();
        String[] strings = {"BASE", "BRONZE", "SILVER", "GOLD"};
        vf.setValues(strings);
        mChart.getXAxis().setValueFormatter(vf);
        mChart.getAxisLeft().setStartAtZero(true);
        mChart.getAxisLeft().setAxisMinValue(0f);

        float[] floats = {0, 0, 0, 0};
        try {
            floats = new float[]{
                    Float.parseFloat(data.getData().getLearning().getBasic()),
                    Float.parseFloat(data.getData().getLearning().getBronze()),
                    Float.parseFloat(data.getData().getLearning().getSilver()),
                    Float.parseFloat(data.getData().getLearning().getGold())};


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

        ArrayList<BarEntry> yVals1 = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            yVals1.add(new BarEntry(i, floats[i]));
        }

        BarDataSet set1;
        set1 = new BarDataSet(yVals1, "");
        set1.setDrawValues(false);
        set1.setColors(Color.parseColor("#475729"), Color.parseColor("#C46C53"), Color.parseColor("#AAAAAA"), Color.parseColor("#E2BB4D"));
        BarData data = new BarData(set1);
        data.setDrawValues(false);
        mChart.setData(data);
        mChart.invalidate();
    }

    private void setAMDetails() {
        areaList.clear();
        areaList.add("All");
        for (int i = 0; i < AM_DATA.getData().size(); i++) {
            areaList.add(AM_DATA.getData().get(i).getName());
        }

        if (areaList == null || areaList.size() == 0) {
            return;
        }

        ArrayAdapter<String> areaAdapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
                R.layout.spinner_region, areaList);
        areaAdapter.setDropDownViewResource(R.layout.spinner_region);
        spinArea.setAdapter(areaAdapter);

        spinArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getAMDashBoard(yearValue, monthValue,
                                ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                "all");
                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                            || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                        getAMDashBoard(yearValue, monthValue, "all",
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                "all");
                    } else {
                        getAMDashBoard(yearValue, monthValue, "all", GlobalData.user.getData().getEmailid(), "all");
                    }
                } else {
                    String email = AM_DATA.getData().get(i - 1).getEmail();
                    GlobalData.amEmail = email;

                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getAMDashBoard(yearValue, monthValue, ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                email);
                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                            || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                        getAMDashBoard(yearValue, monthValue, "all",
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                email);
                    } else {
                        getAMDashBoard(yearValue, monthValue, "all", GlobalData.user.getData().getEmailid(), email);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spinArea.setSelection(0);
    }

    @SuppressLint("NewApi")
    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;
        RectF bounds = mOnValueSelectedRectF;
        mChart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = mChart.getPosition(e, YAxis.AxisDependency.LEFT);
        MPPointF.recycleInstance(position);
    }


    @Override
    public void onNothingSelected() {

    }
}
