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.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.CheckBox;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.qr_code.CameraPreview;
import com.cygnusa.hyperm.qr_code.ScanCallback;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.wrappers.ParticipantList;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.List;
import java.util.Objects;

public class DynamicTabFragment extends Fragment {
    private int byClickPostion = 0;
    View view;
    int val;
    RecyclerView rcvAttendanceContent;
    static AttendanceListAdapeterListAdapter dateAdapter;
    private ValueAnimator mScanAnimator;
    RelativeLayout mScanCropView;
    ImageView mScanLine;
    CameraPreview mPreviewView;
    Dialog aDialog;
    private static final int REQUEST_CODE_SETTING = 1;
    HorizontalScrollView headerScroll;
    int scrollX = 0;

    public static DynamicTabFragment checkTabPosition(int position) {
        DynamicTabFragment fragment = new DynamicTabFragment();
        Bundle args = new Bundle();
        args.putInt("clickPosition", position);
        fragment.setArguments(args);
        return fragment;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
            container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        val = getArguments().getInt("someInt", 0);
        byClickPostion = getArguments().getInt("clickPosition", 0);
        rcvAttendanceContent = view.findViewById(R.id.rcv_attendance_data);
        headerScroll = view.findViewById(R.id.headerScroll);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        // manager.setTotalColumnCount(1);
        rcvAttendanceContent.setLayoutManager(manager);
        rcvAttendanceContent.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getActivity()), DividerItemDecoration.VERTICAL));

        if (byClickPostion == 0 || val == 0) {
            if (GlobalData.fullSingleDataLists.getDateWiseDataList().getSingleDateNineteenList() != null && GlobalData.fullSingleDataLists.getDateWiseDataList().getSingleDateNineteenList().size() > 0) {
                dateAdapter = new AttendanceListAdapeterListAdapter(GlobalData.fullSingleDataLists.getDateWiseDataList().getSingleDateNineteenList().get(0).getParticipant());
            }
        }
        rcvAttendanceContent.setAdapter(dateAdapter);

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


        return view;
    }

    public static DynamicTabFragment addfrag(int val) {
        DynamicTabFragment fragment = new DynamicTabFragment();
        Bundle args = new Bundle();
        args.putInt("someInt", val);
        fragment.setArguments(args);
        return fragment;
    }

    private class AttendanceListAdapeterListAdapter extends RecyclerView.Adapter<DynamicTabFragment.AttendanceViewHolder> {

        List<ParticipantList> singleDateOneList;

        public AttendanceListAdapeterListAdapter(List<ParticipantList> singleDateOneList) {
            this.singleDateOneList = singleDateOneList;
        }

        @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.get(position).getSmpin());
            holder.participantName.setText(singleDateOneList.get(position).getName());
            holder.dealerName.setText(singleDateOneList.get(position).getDealerName());
            holder.smPin.setText(singleDateOneList.get(position).getSmpin());

            holder.btnScan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openScannerDetails();
                }
            });
        }

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

    public static class AttendanceViewHolder extends RecyclerView.ViewHolder {

        TextView smPin, participantName, dealerName, sendCode, enterReason;
        Button btnScan, btnAbsend;
        LinearLayout lloutPictimage;
        CheckBox chkMark;

        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);
            enterReason = itemView.findViewById(R.id.absentreason);
            lloutPictimage = itemView.findViewById(R.id.picimage);
            chkMark = itemView.findViewById(R.id.chkMark);


        }
    }

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

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

        mPreviewView.setScanCallback(resultCallback);

        aDialog.show();
    }


    private ScanCallback resultCallback = new ScanCallback() {
        @Override
        public void onScanResult(String result, Context context) {
            stopScan();
            Log.e("ScanResult", result);
        }
    };

    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) {
                            aDialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @SuppressLint("WrongConstant")
    private void startScanUnKnowPermission() {
        AndPermission.with(this).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(this).runtime().setting().start(REQUEST_CODE_SETTING);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mScanAnimator != null) {
            startScanUnKnowPermission();
        }
    }

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

}
