package com.cygnusa.hyperm.fragments;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.pickimage.util.FixedGridLayoutManager;
import com.cygnusa.hyperm.qr_code.CameraPreview;
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.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GeTSingleDatAttendance;
import com.cygnusa.hyperm.wrappers.ParticipantList;
import com.cygnusa.hyperm.wrappers.ReasonList;
import com.cygnusa.hyperm.wrappers.ReasonListResponse;
import com.cygnusa.hyperm.wrappers.SendAllAttendaceToServer;
import com.cygnusa.hyperm.wrappers.SingleAttendance;
import com.cygnusa.hyperm.wrappers.SingleDateAttendance;
import com.cygnusa.hyperm.wrappers.SingleParticipantList;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

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

import static com.cygnusa.hyperm.AttendanceScheduleActivity.resultCallback;
import static com.cygnusa.hyperm.util.GlobalData.scheduledDataList;
import static com.cygnusa.hyperm.util.GlobalData.singleDateOneList;

public class AMAttendanceMarkingFragment extends androidx.fragment.app.Fragment {
    public static final int REQUEST_CODE_SETTING = 1;
    public static AttendanceListAdapeterList dateAdapter;
    public static CameraPreview mPreviewView;
    public static ValueAnimator mScanAnimator;
    public static Dialog aDialog;
    public static List<SendAllAttendaceToServer> attendanceList = new ArrayList<>();
    public boolean scanResult = false;
    HorizontalScrollView headerScroll;
    RecyclerView rcvDynamicView;
    TextView txtNoDataFound;
    int scrollX = 0;
    LinearLayout tl;
    TextView txtDayCount;
    RelativeLayout mScanCropView;
    ImageView mScanLine;
    // SendAllAttendaceToServer attendance;
    ApiService restService;
    ArrayList<String> dayCount = new ArrayList<>();
    String SCHEDULE_ID = "";
    List<ParticipantList> fulllist = new ArrayList<>();
    String dateFormat = "", submittedDay, clickedDateFormat = "";
    private Button btnSave, btncancel, btnSumbit;
    private TransparentProgressDialog progressDialog;
    private TextView txtDecline;

    private List<ReasonList> REASONS = new ArrayList<>();
    private String[] reasonName = {"None"};
    private String[] reasonId = {"None"};
    private String reasonIdString = "";

    public static void isUpdates() {
        if (dateAdapter != null) {
            dateAdapter.notifyDataSetChanged();
            GlobalData.IMAGECLICKPOS = -1;
            GlobalData.SCANCLICKPOS = -1;
        }
    }

    public void setPresentValue(int position, String reason) {
        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null)
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setIspresent(reason);
        else {
            SingleAttendance attendance = new SingleAttendance();
            attendance.setIspresent(reason);
            attendance.setImage("");
            attendance.setManualAttendanceReason("");
            attendance.setAbsenceReason("");
            attendance.setDay("");
            singleDateOneList.getSingleParticipantList().get(position).setSingleAttendance(attendance);
        }
    }

    private static void stopScan() {
        mScanAnimator.cancel();
        mPreviewView.stop();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.am_fragment_attendance_marking, container, false);
        initViews(view);

        setUpRecyclerView();
        getReasons();


        rcvDynamicView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                scrollX += dx;

                headerScroll.scrollTo(scrollX, 0);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });


        String motnthDate = "";
        int currentMonth = GlobalData.CURRENTMONTH;
        if (currentMonth < 10) {
            motnthDate = "0" + GlobalData.CURRENTMONTH;
        } else {
            motnthDate = String.valueOf(GlobalData.CURRENTMONTH);
        }

        String currentDate = "";
        int day = GlobalData.CURRENTDATE;
        if (day < 10) {
            currentDate = "0" + GlobalData.CURRENTDATE;
        } else {
            currentDate = String.valueOf(GlobalData.CURRENTDATE);
        }

        dateFormat = GlobalData.CURRENTYEAR + "-" + motnthDate + "-" + currentDate;
        clickedDateFormat = currentDate + "-" + motnthDate + "-" + GlobalData.CURRENTYEAR;
        getAllSingleDateAttendance(dateFormat, true);
        int trainingDays = Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays());

        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(GlobalData.STARTDATESTRING));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < trainingDays; i++) {
            final LinearLayout LnrChildLayout = (LinearLayout) getLayoutInflater()
                    .inflate(R.layout.lay_image, null);
            LnrChildLayout.setLayoutParams(new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));

            tl.addView(LnrChildLayout);

            int indexValue = tl.indexOfChild(LnrChildLayout);
            LnrChildLayout.setTag(Integer.toString(indexValue));

            txtDayCount = LnrChildLayout
                    .findViewById(R.id.txtDayCount);

            //setAllDateWise(txtDayCount);

            calendar.set(Calendar.DAY_OF_MONTH, (calendar.get(Calendar.DAY_OF_MONTH) + i));
            String dateString = new SimpleDateFormat("dd-MM-yyyy").format(calendar.getTime());

            int date = i;
            date = date + 1;
            txtDayCount.setText("Day " + date);

            if (dateString.equalsIgnoreCase(clickedDateFormat)) {
                txtDayCount.setEnabled(true);
                int Submittedday = i + 1;
                submittedDay = String.valueOf(Submittedday);
                setDayCount(i);
            } else {
                txtDayCount.setEnabled(true);
                txtDayCount.setAlpha(.5f);
            }


            txtDayCount.setTag(dateString);
            txtDayCount.setId(i);

            int finalI = i;
            txtDayCount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String getDate = (String) v.getTag();
                    String getId = String.valueOf(v.getId());
//                    Toast.makeText(getActivity(),
//                            "Button getTag : >" + strPosition,
//                            Toast.LENGTH_SHORT).show();

                    setDayCount(v.getId());
                    int Submittedday = finalI + 1;
                    submittedDay = String.valueOf(Submittedday);


                    Date currentDate = new Date();
                    Date clicked = null;
                    try {
                        clicked = new SimpleDateFormat("dd-MM-yyyy").parse(getDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if (clickedDateFormat.equalsIgnoreCase(getDate)) {
                        getAllSingleDateAttendance(dateFormat, true);
                    } else if (currentDate.before(clicked)) {
                        GlobalData.showToast(getActivity(), "You cannot mark attendance for upcoming days.", Toast.LENGTH_LONG).show();
                    } else if (currentDate.after(clicked)) {
                        getAllSingleDateAttendance(dateFormat, false);
                    }

//                    dateFormat = GlobalData.CURRENTYEAR + "-" + motnthDate + "-" + strPosition;
//                    int curDate = Integer.parseInt(getDate);
//                    if (curDate == GlobalData.CURRENTDATE)
//                        getAllSingleDateAttendance(dateFormat, true);
//                    else if (curDate < GlobalData.CURRENTDATE)
//                        getAllSingleDateAttendance(dateFormat, false);
//                    else
//                        GlobalData.showToast(getActivity(), "You cannot mark attendance for upcoming days.", Toast.LENGTH_LONG).show();
//                }
                }

            });
        }
        return view;
    }

    private void setDayCount(int getId) {
        dayCount = new ArrayList<>();
        for (int k = 0; k <= getId; k++) {
            dayCount.add("1");
        }
    }

    private void getAllSingleDateAttendance(String date, boolean isEdit) {
        progressDialog.show();
        restService.getSingleDateAttendance(GlobalData.SCHEDULE_ID, date).enqueue(new Callback<GeTSingleDatAttendance>() {
            @Override
            public void onResponse(Call<GeTSingleDatAttendance> call, Response<GeTSingleDatAttendance> response) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (response.body() != null) {
                    if (response.body().getSingleAttendance() != null && response.body().getSingleAttendance().size() > 0) {
                        if (response.body().getSingleAttendance().get(0).getSingleParticipantList() != null && response.body().getSingleAttendance().get(0).getSingleParticipantList().size() > 0) {
                            rcvDynamicView.setVisibility(View.VISIBLE);
                            txtNoDataFound.setVisibility(View.GONE);
                            SingleParticipantList participantList = new SingleParticipantList();
                            ArrayList<SingleParticipantList> participantListArrayList = new ArrayList<>();
                            singleDateOneList = new SingleDateAttendance();
                            SingleParticipantList participantListData;
                            participantListArrayList = new ArrayList<>();
                            if (response.body().getSingleAttendance().get(0).getSingleParticipantList() != null && response.body().getSingleAttendance().get(0).getSingleParticipantList().size() > 0) {

                                singleDateOneList.setScheduleId(response.body().getSingleAttendance().get(0).getScheduleId());
                                singleDateOneList.setScore_submit(response.body().getSingleAttendance().get(0).getScore_submit());
                                singleDateOneList.setLvlId(response.body().getSingleAttendance().get(0).getLvlId());
                                singleDateOneList.setImage(response.body().getSingleAttendance().get(0).getImage());
                                singleDateOneList.setStartDate(response.body().getSingleAttendance().get(0).getStartDate());
                                singleDateOneList.setEndDate(response.body().getSingleAttendance().get(0).getEndDate());
                                singleDateOneList.setAssessmentname(response.body().getSingleAttendance().get(0).getAssessmentname());
                                singleDateOneList.setAssessmenttime(response.body().getSingleAttendance().get(0).getAssessmenttime());
                                singleDateOneList.setScore_submit(response.body().getSingleAttendance().get(0).getScore_submit());
                                singleDateOneList.setLocation(response.body().getSingleAttendance().get(0).getLocation());
                                singleDateOneList.setVenueAm(response.body().getSingleAttendance().get(0).getVenueAm());
                                singleDateOneList.setVenueDealer(response.body().getSingleAttendance().get(0).getVenueDealer());
                                singleDateOneList.setVenueAddress(response.body().getSingleAttendance().get(0).getVenueAddress());
                                singleDateOneList.setIsDeleted(response.body().getSingleAttendance().get(0).getIsDeleted());
                                singleDateOneList.setStatus(response.body().getSingleAttendance().get(0).getStatus());
                                singleDateOneList.setTitle(response.body().getSingleAttendance().get(0).getTitle());
                                singleDateOneList.setOrganizerName(response.body().getSingleAttendance().get(0).getOrganizerName());
                                singleDateOneList.setStartdate(response.body().getSingleAttendance().get(0).getStartdate());
                                singleDateOneList.setEnddate(response.body().getSingleAttendance().get(0).getEnddate());
                                singleDateOneList.setStarttime(response.body().getSingleAttendance().get(0).getStarttime());
                                singleDateOneList.setEndtime(response.body().getSingleAttendance().get(0).getEndtime());
                                singleDateOneList.setTrainingDays(response.body().getSingleAttendance().get(0).getTrainingDays());
                                singleDateOneList.setEndDate(response.body().getSingleAttendance().get(0).getEndDate());
                                singleDateOneList.setAttendance_submit(response.body().getSingleAttendance().get(0).getAttendance_submit());

                                if (singleDateOneList.getAttendance_submit() != null)
                                    if (singleDateOneList.getAttendance_submit().equalsIgnoreCase("1"))
                                        btnSave.setVisibility(View.GONE);
                                    else
                                        btnSave.setVisibility(View.VISIBLE);

                                for (int j = 0; j < response.body().getSingleAttendance().get(0).getSingleParticipantList().size(); j++) {
                                    if (!response.body().getSingleAttendance().get(0).getStatus().equalsIgnoreCase("2")) {
                                        participantList = new SingleParticipantList();
                                        SingleAttendance attendance = new SingleAttendance();

                                        participantListData = response.body().getSingleAttendance().get(0).getSingleParticipantList().get(j);
                                        participantList.setSmpin(participantListData.getSmpin());
                                        participantList.setUserid(participantListData.getUserid());
                                        participantList.setName(participantListData.getName());
                                        participantList.setDealerName(participantListData.getDealerName());
                                        participantList.setAmName(participantListData.getAmName());
                                        participantList.setDealerCode(participantListData.getDealerCode());
                                        participantList.setManualAttendanceReason(participantListData.getManualAttendanceReason());
                                        participantList.setPreTestPercentage(participantListData.getPreTestPercentage());
                                        participantList.setCertification(participantListData.getCertification());
                                        participantList.setPostTestPercentage(participantListData.getPostTestPercentage());
                                        participantList.setRoleplayOrDemo(participantListData.getRoleplayOrDemo());
                                        participantList.setAssignment(participantListData.getAssignment());
                                        participantList.setQrCode(participantListData.getQrCode());
                                        participantList.setRemarks(participantListData.getRemarks());
                                        participantList.setOverall(participantListData.getOverall());
                                        participantList.setAmEmail(participantListData.getAmEmail());
                                        participantList.setPerformance(participantListData.getPerformance());
                                        participantList.setDeclineReason(participantListData.getDeclineReason());
                                        participantList.setDeclineReasonDesc(participantListData.getDeclineReasonDesc());
                                        participantList.setDeclineReasonName(participantListData.getDeclineReasonName());
                                        participantList.setPostTest(participantListData.getPostTest());
                                        participantList.setStatus(participantListData.getStatus());

                                        attendance.setAm_absence_reason_desc(participantListData.getSingleAttendance().getAm_absence_reason_desc());
                                        attendance.setAm_absence_reason(participantListData.getSingleAttendance().getAm_absence_reason());
                                        attendance.setImage(participantListData.getSingleAttendance().getImage());
                                        attendance.setManualAttendanceReason(participantListData.getSingleAttendance().getManualAttendanceReason());
                                        attendance.setIspresent(participantListData.getSingleAttendance().getIspresent());

                                        participantList.setSingleAttendance(attendance);
                                        participantListArrayList.add(participantList);

                                    }
                                }
                                singleDateOneList.setSingleParticipantList(participantListArrayList);
                            }

                            if (singleDateOneList.getSingleParticipantList().size() > 0) {
                                rcvDynamicView.setVisibility(View.VISIBLE);
                                txtNoDataFound.setVisibility(View.GONE);
                                dateAdapter = new AttendanceListAdapeterList(isEdit);
                                rcvDynamicView.setAdapter(dateAdapter);
                            } else {
                                rcvDynamicView.setVisibility(View.GONE);
                                txtNoDataFound.setVisibility(View.VISIBLE);
                            }
                        } else {
                            GlobalData.showToast(getActivity(), response.body().getResponseText(), Toast.LENGTH_LONG).show();
                            rcvDynamicView.setVisibility(View.GONE);
                            txtNoDataFound.setVisibility(View.VISIBLE);
                        }
                    } else if (response.body() != null) {
                        rcvDynamicView.setVisibility(View.GONE);
                        txtNoDataFound.setVisibility(View.VISIBLE);
                        GlobalData.showToast(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    getActivity().finish();
                } 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;
                        getActivity().finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<GeTSingleDatAttendance> call, Throwable t) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });
    }

    private void setUpRecyclerView() {

        FixedGridLayoutManager manager = new FixedGridLayoutManager();
        manager.setTotalColumnCount(1);
        rcvDynamicView.setLayoutManager(manager);
        rcvDynamicView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getActivity()), DividerItemDecoration.VERTICAL));
    }

    private void openSendCodePopup(int position, boolean isEdit, String name, String smpin) {

        Dialog aDialog = new Dialog(getActivity());
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_send_code);
        aDialog.setCancelable(false);

        EditText edtManualReason = aDialog.findViewById(R.id.edtManualReason);

        edtManualReason.setHint("Enter Attendance Code");

        edtManualReason.setInputType(InputType.TYPE_CLASS_NUMBER);
        Button btnOk = aDialog.findViewById(R.id.btnOk);
        TextView txtSubTitle = aDialog.findViewById(R.id.txtSubTitle);

        txtSubTitle.setText(smpin + "-" + name + " would have received attendance code. Get the code and enter in the field below");
        if (!isEdit) {
            btnOk.setVisibility(View.GONE);
            edtManualReason.setEnabled(false);
        }
        Button btnCancel = aDialog.findViewById(R.id.btnCancel);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edtManualReason.getText().toString().trim().isEmpty()) {
                    GlobalData.toast(getActivity(), "Enter Attendance Code");
                } else {
                    setPresentValue(position, "1");
                    dateAdapter.notifyDataSetChanged();
                    aDialog.dismiss();
                }

            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });

        aDialog.show();
    }

    private void openReasonPopup(int position, String reason, boolean isEdit, String name, String smpin) {

        Dialog aDialog = new Dialog(getActivity());
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_absent_reason);
        aDialog.setCancelable(false);

        EditText edtManualReason = aDialog.findViewById(R.id.edtManualReason);
        if (!reason.isEmpty())
            edtManualReason.setText(reason);
        Button btnOk = aDialog.findViewById(R.id.btnOk);
        Button btnCancel = aDialog.findViewById(R.id.btnCancel);

        TextView txtSubTitle = aDialog.findViewById(R.id.txtSubTitle);
        txtSubTitle.setText("Participant Name : " + smpin + "-" + name);

        if (!isEdit) {
            btnOk.setVisibility(View.GONE);
            edtManualReason.setEnabled(false);
        }
        edtManualReason.setEnabled(false);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edtManualReason.getText().toString().trim().isEmpty()) {
                    GlobalData.toast(getActivity(), "Enter reason");
                } else {
                    setClickedDatas(position, edtManualReason.getText().toString());
                    setPresentValue(position, "1");
                    dateAdapter.notifyDataSetChanged();
                    aDialog.dismiss();
                }

            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });

        aDialog.show();

    }

    private void setClickedDatas(int position, String reason) {


        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null)
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setManualAttendanceReason(reason);
        else {
            SingleAttendance attendance = new SingleAttendance();
            attendance.setIspresent("");
            attendance.setImage("");
            attendance.setManualAttendanceReason(reason);
            attendance.setAbsenceReason("");
            attendance.setDay("");
            singleDateOneList.getSingleParticipantList().get(position).setSingleAttendance(attendance);
        }

    }

    private void setAbsentClickedDatas(int position, String reason) {


        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null)
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setAbsenceReason(reason);
        else {
            SingleAttendance attendance = new SingleAttendance();
            attendance.setIspresent("");
            attendance.setImage("");
            attendance.setManualAttendanceReason("");
            attendance.setAbsenceReason(reason);
            attendance.setDay("");
            singleDateOneList.getSingleParticipantList().get(position).setSingleAttendance(attendance);
        }
    }


    private void openAbsentReasonPopup(int position, String absenceReason, String desc, boolean isEdit, String name, String smpin) {

        Dialog aDialog = new Dialog(getActivity());
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.am_view_reason_popup);
        aDialog.setCancelable(false);

        EditText edtManualReason = aDialog.findViewById(R.id.edtReason);

        Button btnOk = aDialog.findViewById(R.id.btnSubmit);
        Button btnCancel = aDialog.findViewById(R.id.btnCancel);
        Button btnClose = aDialog.findViewById(R.id.btnClose);

        TextView txtParticipantName = aDialog.findViewById(R.id.txtParticipantName);
        TextView txtDealerName = aDialog.findViewById(R.id.txtDealerName);
        TextView txtAreaManger = aDialog.findViewById(R.id.txtAreaManger);
        TextView trainerReason = aDialog.findViewById(R.id.trainerReason);


        RelativeLayout rLayoutDecline = aDialog.findViewById(R.id.rLayoutDecline);


        if ((GlobalData.user.getData().getRole().equalsIgnoreCase("14")) ||
                (GlobalData.user.getData().getRole().equalsIgnoreCase("4")) ||
                (GlobalData.user.getData().getRole().equalsIgnoreCase("6"))) {

            rLayoutDecline.setVisibility(View.GONE);
            edtManualReason.setVisibility(View.GONE);
            btnOk.setVisibility(View.GONE);
            btnCancel.setVisibility(View.GONE);
            btnClose.setVisibility(View.VISIBLE);
        }


        txtDecline = aDialog.findViewById(R.id.txtDecline);
        ImageView imgDecline = aDialog.findViewById(R.id.imgDecline);


        String smpin1 = singleDateOneList.getSingleParticipantList().get(position).getSmpin();
        String dseName = singleDateOneList.getSingleParticipantList().get(position).getName();
        String dealerName = singleDateOneList.getSingleParticipantList().get(position).getDealerName();
        String dealerCode = singleDateOneList.getSingleParticipantList().get(position).getDealerCode();
        String amName = singleDateOneList.getSingleParticipantList().get(position).getAmName();

        String trReason = singleDateOneList.getSingleParticipantList().get(position).getAbsenceReason();

        txtParticipantName.setText("Participant Name : " + smpin1 + "-" + dseName);
        txtDealerName.setText("Dealer Name : " + dealerName + "-" + dealerCode);
        txtAreaManger.setText("Area Manger Name : " + amName);
        trainerReason.setText("Reason Given by Trainer : " + trReason);

        if (!absenceReason.isEmpty())
            if (reasonName != null && reasonName.length > 0)
                txtDecline.setText(reasonName[Integer.parseInt(absenceReason) - 1]);

        txtDecline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settitleSelction();
            }
        });

        imgDecline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settitleSelction();
            }
        });

        if (!isEdit) {
            btnOk.setVisibility(View.GONE);
            edtManualReason.setEnabled(false);
        }

        if (!desc.isEmpty())
            edtManualReason.setText(desc);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txtDecline.getText().toString().equalsIgnoreCase("")) {
                    GlobalData.toast(getActivity(), "Select absent reason");
                } else if (edtManualReason.getText().toString().equalsIgnoreCase("")) {
                    GlobalData.toast(getActivity(), "Enter absent reason");
                } else {
                    setAMAbsentClickedDatas(position, reasonIdString, edtManualReason.getText().toString());
                    setPresentValue(position, "0");
                    dateAdapter.notifyDataSetChanged();
                    aDialog.dismiss();
                }

            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });


        aDialog.show();

    }

    private void setAMAbsentClickedDatas(int position, String toString, String manualReason) {

        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null) {
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setAm_absence_reason(toString);
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setAm_absence_reason_desc(manualReason);
        } else {
            SingleAttendance attendance = new SingleAttendance();
            attendance.setIspresent("");
            attendance.setImage("");
            attendance.setManualAttendanceReason("");
            attendance.setAbsenceReason("");
            attendance.setDay("");
            attendance.setAm_absence_reason(toString);
            attendance.setAm_absence_reason_desc(manualReason);
            singleDateOneList.getSingleParticipantList().get(position).setSingleAttendance(attendance);
        }

    }

    private void getReasons() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            try {
                restService.getReasonList().enqueue(new Callback<ReasonListResponse>() {
                    @Override
                    public void onResponse(Call<ReasonListResponse> call, Response<ReasonListResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                REASONS = response.body().getData();
                                reasonName = new String[REASONS.size()];
                                reasonId = new String[REASONS.size()];
                                for (int i = 0; i < response.body().getData().size(); i++) {
                                    reasonName[i] = REASONS.get(i).getName();
                                    reasonId[i] = REASONS.get(i).getId();
                                }
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                        } 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;
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ReasonListResponse> call, Throwable t) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void settitleSelction() {
        int selection = 0;

        if (!txtDecline.getText().toString().isEmpty()) {
            selection = Arrays.asList(reasonName).indexOf(txtDecline.getText().toString().trim());
        }
        new android.app.AlertDialog.Builder(getActivity()).setTitle("Reason for Reschedule")
                .setSingleChoiceItems(reasonName, selection, null)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", (dialog, whichButton) -> {
                    dialog.dismiss();
                    int selectedPosition = ((android.app.AlertDialog) dialog).getListView().getCheckedItemPosition();
                    txtDecline.setText(reasonName[selectedPosition]);
                    reasonIdString = reasonId[selectedPosition];
                })
                .show();

    }

    private void openScannerDetails() {

        aDialog = new Dialog(getActivity());
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_select_camera);
        aDialog.setCancelable(true);


        mPreviewView = aDialog.findViewById(R.id.capture_preview);
        mScanCropView = aDialog.findViewById(R.id.capture_crop_view);
        mScanLine = aDialog.findViewById(R.id.capture_scan_line);

        Button btncancel = aDialog.findViewById(R.id.btncancel);
        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });

        if (mScanAnimator == null) {
            int height = mScanCropView.getMeasuredHeight() - 25;
            mScanAnimator = ObjectAnimator.ofFloat(mScanLine, "translationY", 0F, height).setDuration(3000);
            mScanAnimator.setInterpolator(new LinearInterpolator());
            mScanAnimator.setRepeatCount(ValueAnimator.INFINITE);
            mScanAnimator.setRepeatMode(ValueAnimator.REVERSE);
            startScanUnKnowPermission();
        }
        if (mScanAnimator != null) {
            startScanUnKnowPermission();
        }
        mPreviewView.setScanCallback(resultCallback);

        aDialog.show();
    }

    private void sendAttendanceDetailsToSever(SingleDateAttendance fulllist) {

        ArrayList<HashMap<String, String>> attendanceList = new ArrayList();
        HashMap<String, String> attendanceValueMap = new HashMap<>();
        if (fulllist.getSingleParticipantList().size() > 0) {
            for (int k = 0; k < fulllist.getSingleParticipantList().size(); k++) {

                if (fulllist.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().equalsIgnoreCase("0")) {
                    if (fulllist.getSingleParticipantList().get(k).getSingleAttendance().getAm_absence_reason() == null || fulllist.getSingleParticipantList().get(k).getSingleAttendance().getAm_absence_reason().isEmpty()) {
                        GlobalData.toast(getActivity(), "Kindly select reason for absentees");
                        return;
                    }
                }

                attendanceValueMap = new HashMap<>();
                if (fulllist.getSingleParticipantList().get(k).getSingleAttendance() != null) {
                    attendanceValueMap.put("am_absence_reason", fulllist.getSingleParticipantList().get(k).getSingleAttendance().getAm_absence_reason());
                    attendanceValueMap.put("am_absence_reason_desc", fulllist.getSingleParticipantList().get(k).getSingleAttendance().getAm_absence_reason_desc());
                    attendanceValueMap.put("userid", fulllist.getSingleParticipantList().get(k).getUserid());
                }

                attendanceList.add(attendanceValueMap);
            }
        }


        Gson gson = new Gson();
        JsonElement jsonElement = gson.toJsonTree(
                attendanceList, new TypeToken<ArrayList<String>>() {
                }.getType());

        HashMap<String, String> map = new HashMap<>();
        map.put("absent_reason", jsonElement.toString());
        map.put("schedule_id", GlobalData.SCHEDULE_ID);
        map.put("am_acknowledgement", dayCount.toString());
        Log.e("mapResonse", attendanceList.toString());
        restService.sendAMAttendanceDetailsToServer(map).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (response.body().getResponse().equalsIgnoreCase("Success")) {
                        GlobalData.toast(getActivity(), response.body().getMessage());
                        getActivity().onBackPressed();
                    } else {
                        GlobalData.toast(getActivity(), response.body().getMessage());
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    Objects.requireNonNull(getActivity()).finish();
                } 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;
                        getActivity().finish();
                    }
                }
            }

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

            }
        });
    }

    private void startScanWithPermission() {
        if (mPreviewView.start()) {
            mScanAnimator.start();
        } else {
            new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.camera_failure)
                    .setMessage(R.string.camera_hint)
                    .setCancelable(false)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @SuppressLint("WrongConstant")
    public void startScanUnKnowPermission() {
        AndPermission.with(getActivity()).runtime().permission(Manifest.permission.CAMERA).onGranted(permissions -> {
            startScanWithPermission();
        }).onDenied(permissions -> {
            if (AndPermission.hasAlwaysDeniedPermission(getActivity(), permissions)) {
                showSettingDialog(getActivity(), permissions);
            }
        }).start();
    }

    public void showSettingDialog(Context context, final List<String> permissions) {
        List<String> permissionNames = Permission.transformText(context, permissions);
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"}) String message = context.getString(R.string.message_permission_always_failed,
                TextUtils.join("\n", permissionNames));

        new AlertDialog.Builder(context).setCancelable(false)
                .setTitle(R.string.permission_name_camera)
                .setMessage(message)
                .setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPermission();
                    }
                })
                .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }

    private void setPermission() {
        AndPermission.with(getActivity()).runtime().setting().start(REQUEST_CODE_SETTING);
    }

    private void initViews(View view) {
        restService = ((MainApplication) Objects.requireNonNull(getActivity()).getApplicationContext()).getClient();
        tl = view.findViewById(R.id.lloutAddButton);
        headerScroll = view.findViewById(R.id.headerScroll);
        rcvDynamicView = view.findViewById(R.id.rcvDynamicView);
        txtNoDataFound = view.findViewById(R.id.txtNoDataFound);
        txtNoDataFound.setVisibility(View.GONE);
        progressDialog = new TransparentProgressDialog(getActivity());
        btnSave = view.findViewById(R.id.btnSave);
        if (GlobalData.scheduledDataList.get(0).getCurrent_attendance_submit_status() != null && !GlobalData.scheduledDataList.get(0).getCurrent_attendance_submit_status().isEmpty())
            if (GlobalData.scheduledDataList.get(0).getCurrent_attendance_submit_status().equalsIgnoreCase("1")) {
                btnSave.setEnabled(true);
                btnSave.setAlpha(1f);
            } else {
                btnSave.setEnabled(false);
                btnSave.setAlpha(.5f);
            }
        if (scheduledDataList.get(0).getCurrent_am_acknowledgement_status() != null && !scheduledDataList.get(0).getCurrent_am_acknowledgement_status().isEmpty())
            if (scheduledDataList.get(0).getCurrent_am_acknowledgement_status().equalsIgnoreCase("1")) {
                btnSave.setEnabled(false);
                btnSave.setAlpha(.5f);
            }
        if (scheduledDataList.get(0).getScoreSubmit() != null && !scheduledDataList.get(0).getScoreSubmit().isEmpty())
            if (scheduledDataList.get(0).getScoreSubmit().equalsIgnoreCase("2")) {
                btnSave.setEnabled(false);
                btnSave.setAlpha(.5f);
            }

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendAttendanceDetailsToSever(singleDateOneList);
            }
        });
    }

    public static class AttendanceViewHolder extends RecyclerView.ViewHolder {

        TextView smPin, participantName, dealerName, sendCode, absentreason, txtManualAttendance, txtDeclineReason;
        Button btnScan, btnAbsend;
        LinearLayout lloutPictimage;
        private ImageView imgPhoto;

        public AttendanceViewHolder(@NonNull View itemView) {
            super(itemView);
            smPin = itemView.findViewById(R.id.smpin);
            participantName = itemView.findViewById(R.id.participant_name);
            dealerName = itemView.findViewById(R.id.dealername);
            btnScan = itemView.findViewById(R.id.btnscan);
            btnAbsend = itemView.findViewById(R.id.btnabsent);
            sendCode = itemView.findViewById(R.id.entercode);
            absentreason = itemView.findViewById(R.id.absentreason);
            lloutPictimage = itemView.findViewById(R.id.picimage);
            imgPhoto = itemView.findViewById(R.id.imgPhoto);
            txtManualAttendance = itemView.findViewById(R.id.txtManualAttendance);
            txtDeclineReason = itemView.findViewById(R.id.txtDeclineReason);


            btnAbsend.setEnabled(true);
            btnAbsend.setAlpha(1f);
            absentreason.setEnabled(true);
            absentreason.setAlpha(1f);

            txtManualAttendance.setEnabled(false);
            txtManualAttendance.setClickable(false);
            txtManualAttendance.setAlpha(.8f);

            imgPhoto.setEnabled(false);
            imgPhoto.setAlpha(.8f);
            imgPhoto.setEnabled(false);

            btnScan.setEnabled(false);
            sendCode.setEnabled(false);
            btnScan.setAlpha(.8f);
            sendCode.setAlpha(.8f);
            lloutPictimage.setClickable(false);
            lloutPictimage.setEnabled(false);

        }
    }

    private class AttendanceListAdapeterList extends RecyclerView.Adapter<AttendanceViewHolder> {

        boolean isEdit = false;

        public AttendanceListAdapeterList(boolean isEdit) {
            this.isEdit = isEdit;
        }

        @NonNull
        @Override
        public AttendanceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.am_attendance_view_holder, parent, false);
            return new AttendanceViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull AttendanceViewHolder holder, int position) {
            holder.smPin.setText(singleDateOneList.getSingleParticipantList().get(position).getSmpin());
            holder.participantName.setText(singleDateOneList.getSingleParticipantList().get(position).getName());
            holder.dealerName.setText(singleDateOneList.getSingleParticipantList().get(position).getAmName() + " - " + singleDateOneList.getSingleParticipantList().get(position).getDealerCode() + " - " + singleDateOneList.getSingleParticipantList().get(position).getDealerName());

            if (singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonName() != null && !singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonName().isEmpty()) {
                holder.txtDeclineReason.setText(singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonName());
                holder.txtDeclineReason.setTextColor(getResources().getColor(R.color.red));
            } else if (singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonDesc() != null && !singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonDesc().isEmpty()) {
                holder.txtDeclineReason.setText(singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonName() + " - " + singleDateOneList.getSingleParticipantList().get(position).getDeclineReasonDesc());
                holder.txtDeclineReason.setTextColor(getResources().getColor(R.color.red));
            } else {
                holder.txtDeclineReason.setText("-");
                holder.txtDeclineReason.setTextColor(getResources().getColor(R.color.red));
            }

            if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null) {

                if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getImage() != null && !singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getImage().isEmpty()) {

                    holder.imgPhoto.setLayoutParams(
                            new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT,
                                    LinearLayout.LayoutParams.MATCH_PARENT));
                    holder.imgPhoto.setPadding(0, 10, 0, 10);

                    Glide.with(getActivity()).load(singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getImage())
                            .thumbnail(Glide.with(getActivity()).load(R.drawable.gif_loader))
                            .into(holder.imgPhoto);
                } else {
                    holder.imgPhoto.setLayoutParams(
                            new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT,
                                    LinearLayout.LayoutParams.MATCH_PARENT));
                    holder.imgPhoto.setPadding(0, 10, 0, 10);
                    Glide.with(getActivity()).load(R.drawable.camera)
                            .thumbnail(Glide.with(getActivity()).load(R.drawable.camera))
                            .into(holder.imgPhoto);
                }

                if (singleDateOneList.getSingleParticipantList().get(position) != null && singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getManualAttendanceReason() != null && !singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getManualAttendanceReason().isEmpty()) {
                    holder.txtManualAttendance.setText("View Reason");
                } else {
                    holder.txtManualAttendance.setText("No Reason");
                }

                if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getAbsenceReason() != null && !singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getAbsenceReason().isEmpty()) {
                    holder.absentreason.setText("View Reason");
                } else {
                    holder.absentreason.setText("Reason");
                }

                if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getIspresent() != null && !singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getIspresent().isEmpty()) {
                    if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getIspresent().equalsIgnoreCase("1")) {
                        holder.btnScan.setText("Present");
                        holder.btnScan.setBackground(getResources().getDrawable(R.drawable.border_full_green));
                        holder.btnAbsend.setBackground(getResources().getDrawable(R.drawable.border_full_gray));
                        holder.sendCode.setVisibility(View.INVISIBLE);

                        holder.btnAbsend.setEnabled(false);
                        holder.btnAbsend.setAlpha(.7f);
                        holder.absentreason.setEnabled(false);
                        holder.absentreason.setAlpha(.7f);


                    } else if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getIspresent().equalsIgnoreCase("0")) {
                        holder.btnScan.setText("Scan");
                        holder.btnScan.setBackground(getResources().getDrawable(R.drawable.border_full_blue));
                        holder.btnAbsend.setBackground(getResources().getDrawable(R.drawable.border_full_red));
                        holder.sendCode.setVisibility(View.VISIBLE);
                        holder.btnAbsend.setEnabled(true);
                        holder.btnAbsend.setAlpha(1f);
                        holder.absentreason.setEnabled(true);
                        holder.absentreason.setAlpha(1f);

                    }
                } else {
                    holder.btnScan.setText("Scan");
                    holder.btnScan.setBackground(getResources().getDrawable(R.drawable.border_full_blue));
                    holder.btnAbsend.setBackground(getResources().getDrawable(R.drawable.border_full_gray));
                    holder.sendCode.setVisibility(View.VISIBLE);
                    holder.btnAbsend.setEnabled(false);
                    holder.btnAbsend.setAlpha(.7f);
                    holder.absentreason.setEnabled(false);
                    holder.absentreason.setAlpha(.7f);
                }
            }


            holder.txtManualAttendance.setTag(position);
            holder.txtManualAttendance.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance() != null)
                        if (singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getManualAttendanceReason() != null && !singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getManualAttendanceReason().isEmpty()) {
                            openReasonPopup((Integer) v.getTag(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getManualAttendanceReason(), isEdit, singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getName(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSmpin());
                        }
                }
            });

            holder.absentreason.setTag(position);
            holder.absentreason.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance() != null)
                        if (singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAm_absence_reason() != null && !singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAm_absence_reason().isEmpty())

                            openAbsentReasonPopup((Integer) v.getTag(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAm_absence_reason(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAm_absence_reason_desc(), isEdit, singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getName(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSmpin());
                        else
                            openAbsentReasonPopup((Integer) v.getTag(), "", "", isEdit, singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getName(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSmpin());
                }
            });

        }

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