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.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Base64;
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.ClassRoomTrainerTainingActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.pickimage.util.FixedGridLayoutManager;
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.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GeTSingleDatAttendance;
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 com.yanzhenjie.zbar.camera.CameraPreview;
import com.yanzhenjie.zbar.camera.ScanCallback;

import java.io.ByteArrayOutputStream;
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.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.singleDateOneList;

public class TrainingAttendanceMarkingFragment extends androidx.fragment.app.Fragment {
    public static final int REQUEST_CODE_SETTING = 1;
    public static AttendanceListAdapeterListAdapter dateAdapter;
    public static CameraPreview mPreviewView;
    public static ValueAnimator mScanAnimator;
    public static Dialog aDialog;
    private static final int CAMERA_REQUEST = 1888;
    public static List<SendAllAttendaceToServer> attendanceList = new ArrayList<>();

    public boolean scanResult = false;
    HorizontalScrollView headerScroll;
    RecyclerView rcvDynamicView;
    TextView txtNoDataFound;
    int scrollX = 0;
    byte[] decodedString;
    LinearLayout tl;
    TextView txtDayCount;
    RelativeLayout mScanCropView;
    ImageView mScanLine;
    // SendAllAttendaceToServer attendance;
    ApiService restService;
    ArrayList<String> dayCount = new ArrayList<>();
    String SCHEDULE_ID = "";
    String dateFormat = "", submittedDay, clickedDateFormat = "";
    private Button btnSave, btncancel, btnSumbit;
    private TransparentProgressDialog progressDialog;

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

    public static void setPresentValue(int position, String reason) {
        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null) {
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setIspresent(reason);
            if (reason.equalsIgnoreCase("0")) {
                singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setImage("");
                singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setBitmapImage("");
            }
        } 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.fragment_attendance_marking, container, false);
        initViews(view);

        setUpRecyclerView();


        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(Submittedday);
            } else {
                txtDayCount.setEnabled(true);
                txtDayCount.setAlpha(.5f);
            }


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

            int finalI = txtDayCount.getId();
            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();


                    int Submittedday = finalI + 1;
                    submittedDay = String.valueOf(Submittedday);
                    setDayCount(v.getId());
                    for (int i = 0; i < tl.getChildCount(); i++) {
                        View child = tl.getChildAt(i);
                        if (i == finalI) {
                            child.setBackground(getResources().getDrawable(R.drawable.border_navi));
                        } else {
                            child.setBackground(getResources().getDrawable(R.drawable.border_full_gray));
                        }
                    }

                    //txtDayCount.setTextColor(getResources().getColor(R.color.mdtp_red_focused));

                    Date currentDate = new Date();
                    Date clicked = null;
                    String clickedReverseDate = "";
                    try {
                        clicked = new SimpleDateFormat("dd-MM-yyyy").parse(getDate);

                        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                        clickedReverseDate = sdf2.format(sdf.parse(getDate));
                    } catch (ParseException e) {
                        //  e.printStackTrace();
                    }
                    if (clickedDateFormat.equalsIgnoreCase(getDate)) {
                        rcvDynamicView.setVisibility(View.VISIBLE);
                        txtNoDataFound.setVisibility(View.GONE);
                        getAllSingleDateAttendance(dateFormat, true);
                    } else if (currentDate.before(clicked)) {
                        GlobalData.showToast(getActivity(), "You cannot mark attendance for upcoming days.", Toast.LENGTH_SHORT).show();
                        rcvDynamicView.setVisibility(View.GONE);
                        txtNoDataFound.setVisibility(View.VISIBLE);
                    } else if (currentDate.after(clicked)) {
                        rcvDynamicView.setVisibility(View.VISIBLE);
                        txtNoDataFound.setVisibility(View.GONE);
                        getAllSingleDateAttendance(clickedReverseDate, 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<>();
        int k = 0;
        for (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;
                            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.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());
                                for (int j = 0; j < response.body().getSingleAttendance().get(0).getSingleParticipantList().size(); j++) {
                                    if (!response.body().getSingleAttendance().get(0).getSingleParticipantList().get(j).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 AttendanceListAdapeterListAdapter(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);
                    }
                } 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);
    }

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

        HashMap<String, String> map = new HashMap<>();
        map.put("userid", userid);
        map.put("schedule_id", GlobalData.SCHEDULE_ID);

        restService.trainingattendancenotification(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")) {
                        Log.e("CommonResponse", response.body().getMessage());
                        openSendCodePopup(position, isEdit, name, smpin);
                    }
                } 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<CommonResponse> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("Message", t.getMessage());
                }
            }
        });
    }

    private void checkOtp(int position, String smpin, Dialog aDialog, String otp) {

        HashMap<String, String> map = new HashMap<>();
        map.put("userid", smpin);
        map.put("schedule_id", GlobalData.SCHEDULE_ID);
        map.put("otp", otp);


        restService.trainingattendancenotificationUpdate(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")) {
                        setPresentValue(position, "1");
                        dateAdapter.notifyDataSetChanged();
                        aDialog.dismiss();
                    } else {
                        Toast.makeText(getActivity(), "Invalid OTP", Toast.LENGTH_LONG).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<CommonResponse> call, Throwable t) {

            }
        });

    }

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

                    checkOtp(position, singleDateOneList.getSingleParticipantList().get(position).getUserid(), aDialog, edtManualReason.getText().toString());
                }

            }
        });

        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);
        TextView heading = aDialog.findViewById(R.id.heading);
        heading.setText("Manual Reason");
        txtSubTitle.setText("Participant Name : " + smpin + "-" + name);

        if (!isEdit) {
            btnOk.setVisibility(View.GONE);
            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) {

                dateAdapter.notifyDataSetChanged();
                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, 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);

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

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

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

            }
        });

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

        aDialog.show();

    }

    private void openScannerDetails() {

        aDialog = new Dialog(getActivity());
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_scan_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();
            }
        });
        try {
            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((ScanCallback) resultCallback);
        } catch (Exception e) {
            Log.e("Scan Result", e.toString(), e);
        }
        aDialog.show();
    }

    private void sendAttendanceDetailsToSever(String s) {


        if (s.equalsIgnoreCase("1")) {
            if (singleDateOneList.getSingleParticipantList().size() > 0) {
                for (int k = 0; k < singleDateOneList.getSingleParticipantList().size(); k++) {
                    if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance() == null || singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent() == null || singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().isEmpty()) {
                        GlobalData.toast(getActivity(), "Kindly Enter all attendance details.");
                        return;
                    }
                }
            }
        }

        for (int k = 0; k < singleDateOneList.getSingleParticipantList().size(); k++) {
            if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance() != null)
                if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent() != null
                        && !singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().isEmpty()) {
                    if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().equalsIgnoreCase("1")) {
                        if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getImage() == null || singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getImage().equalsIgnoreCase("")) {
                            GlobalData.toast(getActivity(), "Kindly Upload image for all present DSE's");
                            return;
                        }
                    }
                }
        }

        progressDialog.show();
        ArrayList<HashMap<String, String>> attendanceList = new ArrayList();
        HashMap<String, String> attendanceValueMap;
        if (singleDateOneList.getSingleParticipantList().size() > 0) {
            for (int k = 0; k < singleDateOneList.getSingleParticipantList().size(); k++) {
                attendanceValueMap = new HashMap<>();
                if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance() != null)


                    if (s.equalsIgnoreCase("1")) {
                        if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent() != null
                                && !singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().isEmpty()) {
                            if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().equalsIgnoreCase("1")) {
                                if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getBitmapImage() != null && !singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getBitmapImage().isEmpty()) {
                                    attendanceValueMap.put("upload_photo", singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getBitmapImage());
                                } else {
                                    attendanceValueMap.put("upload_photo", "");
                                }
                            } else {
                                attendanceValueMap.put("upload_photo", "");
                            }
                            attendanceValueMap.put("day", submittedDay);
                            attendanceValueMap.put("ispresent", singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent());
                            attendanceValueMap.put("userid", singleDateOneList.getSingleParticipantList().get(k).getUserid());
                            attendanceValueMap.put("manual_attendance_reason", singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getManualAttendanceReason());
                            attendanceValueMap.put("absence_reason", singleDateOneList.getSingleParticipantList().get(k).getAbsenceReason());
                            attendanceList.add(attendanceValueMap);
                        } else {
                            attendanceValueMap.put("upload_photo", "");
                            attendanceValueMap.put("day", submittedDay);
                            attendanceValueMap.put("ispresent", "0");
                            attendanceValueMap.put("userid", singleDateOneList.getSingleParticipantList().get(k).getUserid());
                            attendanceValueMap.put("manual_attendance_reason", "");
                            attendanceValueMap.put("absence_reason", "No reason given by trainer");
                            attendanceList.add(attendanceValueMap);
                        }
                    } else {
                        if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent() != null
                                && !singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().isEmpty()) {
                            if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent().equalsIgnoreCase("1")) {
                                if (singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getBitmapImage() != null && !singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getBitmapImage().isEmpty()) {
                                    attendanceValueMap.put("upload_photo", singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getBitmapImage());
                                } else {
                                    attendanceValueMap.put("upload_photo", "");
                                }
                            } else {
                                attendanceValueMap.put("upload_photo", "");
                            }
                            attendanceValueMap.put("day", submittedDay);
                            attendanceValueMap.put("ispresent", singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getIspresent());
                            attendanceValueMap.put("userid", singleDateOneList.getSingleParticipantList().get(k).getUserid());
                            attendanceValueMap.put("manual_attendance_reason", singleDateOneList.getSingleParticipantList().get(k).getSingleAttendance().getManualAttendanceReason());
                            attendanceValueMap.put("absence_reason", singleDateOneList.getSingleParticipantList().get(k).getAbsenceReason());
                            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("attendance", jsonElement.toString());
        map.put("schedule_id", GlobalData.SCHEDULE_ID);
        if (s.equalsIgnoreCase("1"))
            map.put("attendance_submit", dayCount.toString());
        Log.e("mapResonse", attendanceList.toString());
        restService.sendAttendanceDetailsToServer(map).

                enqueue(new Callback<CommonResponse>() {
                    @Override
                    public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null) {
                            if (response.body().getResponse().equalsIgnoreCase("Success")) {
                                if (s.equalsIgnoreCase("1")) {
                                    Toast.makeText(getActivity(), "Submitted Successfully", Toast.LENGTH_LONG).show();

                                } else {
                                    Toast.makeText(getActivity(), "Saved Successfully", Toast.LENGTH_LONG).show();
                                }
                                startActivity(new Intent(getActivity(), ClassRoomTrainerTainingActivity.class));
                                getActivity().finish();
                            } 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) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }
                });
    }

    private String getEnodeString(Bitmap bitmapImage) {

        String encodedDigitalSign = "";
        if (bitmapImage != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            encodedDigitalSign = Base64.encodeToString(byteArray, Base64.DEFAULT);
        }
        return "data:image/jpeg;base64," + encodedDigitalSign;
    }

    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);
        btncancel = view.findViewById(R.id.btncancel);
        btnSumbit = view.findViewById(R.id.btnsubmit);


        if (GlobalData.scheduledDataList.get(0).getAttendanceUpdateStatus() != null)
            if (GlobalData.scheduledDataList.get(0).getAttendanceUpdateStatus().equalsIgnoreCase("0"))
                btnSumbit.setVisibility(View.GONE);

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

                sendAttendanceDetailsToSever("1");
            }
        });
        rcvDynamicView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getActivity()), DividerItemDecoration.VERTICAL));

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

        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Objects.requireNonNull(getActivity()).onBackPressed();
            }
        });

        if (GlobalData.scheduledDataList.get(0).getCurrent_attendance_submit_status().equalsIgnoreCase("1")) {
            btnSumbit.setVisibility(View.VISIBLE);
            btnSave.setVisibility(View.GONE);
            btnSumbit.setText("Attendance submitted");
            btnSumbit.setPadding(3, 0, 3, 0);
            btnSumbit.setEnabled(false);
            btnSumbit.setAlpha(.7f);
        } else {
            btnSumbit.setVisibility(View.VISIBLE);
            btnSave.setVisibility(View.VISIBLE);
        }
    }

    public static class AttendanceViewHolder extends RecyclerView.ViewHolder {

        TextView smPin, participantName, dealerName, sendCode, absentreason;
        Button btnScan, btnAbsend;
        LinearLayout lloutPictimage;
        Button chkMark;
        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);
            chkMark = itemView.findViewById(R.id.chkMark);
            //  txtAmReason = itemView.findViewById(R.id.txtAmReason);
            imgPhoto = itemView.findViewById(R.id.imgPhoto);

        }
    }

    private class AttendanceListAdapeterListAdapter extends RecyclerView.Adapter<AttendanceViewHolder> {

        boolean isEdit = false;

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

        @NonNull
        @Override
        public AttendanceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.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).getDealerCode() + "-" + singleDateOneList.getSingleParticipantList().get(position).getDealerName() + "-" + singleDateOneList.getSingleParticipantList().get(position).getAmName());

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

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

                if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getImage() != null &&
                        !singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getImage().isEmpty()) {
                    Glide.with(getActivity()).load(singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().getImage())
                            .thumbnail(Glide.with(getActivity()).load(R.drawable.gif_loader))
                            .into(holder.imgPhoto);
                } else {
                    Glide.with(getActivity()).load(R.drawable.camera)
                            .thumbnail(Glide.with(getActivity()).load(R.drawable.camera))
                            .into(holder.imgPhoto);
                }


                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.imgPhoto.setEnabled(true);
                        holder.lloutPictimage.setEnabled(true);

                        holder.chkMark.setEnabled(true);
                        holder.chkMark.setClickable(true);

                        holder.chkMark.setAlpha(1f);
                        holder.imgPhoto.setAlpha(1f);
                        holder.lloutPictimage.setAlpha(1f);
                    } 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.imgPhoto.setEnabled(false);
                        holder.lloutPictimage.setEnabled(false);

                        holder.chkMark.setEnabled(false);
                        holder.chkMark.setClickable(false);
                        holder.chkMark.setAlpha(.8f);

                        holder.imgPhoto.setAlpha(.8f);
                        holder.lloutPictimage.setAlpha(.8f);
                    }
                } 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);

                    if (GlobalData.scheduledDataList.get(0).getAttendanceUpdateStatus().equalsIgnoreCase("0")) {
                        holder.imgPhoto.setEnabled(false);
                        holder.lloutPictimage.setEnabled(false);

                        holder.chkMark.setEnabled(false);
                        holder.chkMark.setClickable(false);

                        holder.chkMark.setAlpha(.8f);
                        holder.imgPhoto.setAlpha(.8f);
                        holder.lloutPictimage.setAlpha(.8f);
                    } else {
                        holder.imgPhoto.setEnabled(true);
                        holder.lloutPictimage.setEnabled(true);

                        holder.chkMark.setEnabled(true);
                        holder.chkMark.setClickable(true);

                        holder.chkMark.setAlpha(1f);
                        holder.imgPhoto.setAlpha(1f);
                        holder.lloutPictimage.setAlpha(1f);
                    }
                }
            }


            if (!isEdit) {
                holder.sendCode.setEnabled(false);
                holder.btnScan.setEnabled(false);
                holder.btnAbsend.setEnabled(false);
                holder.btnScan.setAlpha(.8f);
                holder.sendCode.setAlpha(.8f);
                holder.absentreason.setAlpha(.8f);
                holder.btnAbsend.setAlpha(.8f);
                holder.chkMark.setEnabled(false);
                holder.chkMark.setAlpha(.8f);
                holder.chkMark.setClickable(false);
                holder.absentreason.setEnabled(false);
                holder.lloutPictimage.setEnabled(false);
                holder.lloutPictimage.setClickable(false);
            }

            if (GlobalData.scheduledDataList.get(0).getCurrent_attendance_submit_status().equalsIgnoreCase("1")) {
                holder.btnAbsend.setEnabled(false);
                holder.btnAbsend.setAlpha(.8f);
                holder.absentreason.setEnabled(false);
                holder.absentreason.setAlpha(.8f);

                holder.chkMark.setEnabled(false);
                holder.chkMark.setClickable(false);
                holder.chkMark.setAlpha(.8f);
                holder.imgPhoto.setEnabled(false);
                holder.imgPhoto.setAlpha(.8f);
                holder.imgPhoto.setEnabled(false);

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

            }

            holder.sendCode.setTag(position);
            holder.sendCode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getOtpForAttendance((Integer) v.getTag(), isEdit, singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getUserid(), 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().getAbsenceReason() != null && !singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAbsenceReason().isEmpty())

                            openAbsentReasonPopup((Integer) v.getTag(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAbsenceReason(), 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());
                }
            });

            holder.chkMark.setTag(position);

            holder.chkMark.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());
                        } else {
                            openReasonPopup((Integer) v.getTag(), "", isEdit, singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getName(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSmpin());
                        }
                    } else {
                        openReasonPopup((Integer) v.getTag(), "", isEdit, singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getName(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSmpin());
                    }
                }
            });

            holder.btnAbsend.setTag(position);
            holder.btnAbsend.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().getAbsenceReason() != null && !singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAbsenceReason().isEmpty())

                            openAbsentReasonPopup((Integer) v.getTag(), singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getSingleAttendance().getAbsenceReason(), 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());

                }
            });

            holder.btnScan.setTag(position);
            holder.btnScan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!holder.btnScan.getText().toString().equalsIgnoreCase("Present")) {
                        GlobalData.SCANCLICKPOS = (Integer) v.getTag();
                        GlobalData.QRCODEVALUE = singleDateOneList.getSingleParticipantList().get((Integer) v.getTag()).getQrCode();
                        dateAdapter.notifyDataSetChanged();
                        openScannerDetails();
                    }
                }
            });

            holder.lloutPictimage.setTag(position);
            holder.lloutPictimage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GlobalData.IMAGECLICKPOS = (Integer) v.getTag();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, CAMERA_REQUEST);
                }
            });

        }

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