package com.cygnusa.hyperm.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
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.wrappers.DSEResultAndScore;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllDSEResultAndScore;

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

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

public class DSEResultScoreFragment extends Fragment {

    HorizontalScrollView headerScroll;
    RecyclerView rcvDynamicView;
    TextView txtNoDataFound;
    int scrollX = 0;
    public DseScoreAdapter scoreAdapter;
    ApiService restService;

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

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

    private void setUpRecyclerView() {

        FixedGridLayoutManager manager = new FixedGridLayoutManager();
        manager.setTotalColumnCount(1);
        rcvDynamicView.setLayoutManager(manager);
    }

    private void initView(View view) {
        headerScroll = view.findViewById(R.id.headerScroll);
        rcvDynamicView = view.findViewById(R.id.rcvDynamicView);
        txtNoDataFound = view.findViewById(R.id.txtNoDataFound);
        txtNoDataFound.setVisibility(View.GONE);
        restService = ((MainApplication) getActivity().getApplication()).getClient();


        getDseFeedbackResultScore();
    }

    private void getDseFeedbackResultScore() {
        restService.dseFeedbackResultAndscore().enqueue(new Callback<GetAllDSEResultAndScore>() {
            @Override
            public void onResponse(Call<GetAllDSEResultAndScore> call, Response<GetAllDSEResultAndScore> response) {
                if (response.body() != null) {
                    if (response.body().getMessage().equalsIgnoreCase("Success")) {
                        if (response.body().getDseResultAndScoreList() != null && response.body().getDseResultAndScoreList().size() > 0) {
                            scoreAdapter = new DseScoreAdapter(response.body().getDseResultAndScoreList());
                            rcvDynamicView.setAdapter(scoreAdapter);
                        } else {
                            rcvDynamicView.setVisibility(View.GONE);
                            txtNoDataFound.setVisibility(View.VISIBLE);
                        }
                    } else {
                        GlobalData.toast(getActivity(), response.body().getMessage());
                        rcvDynamicView.setVisibility(View.GONE);
                        txtNoDataFound.setVisibility(View.VISIBLE);
                    }
                } 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<GetAllDSEResultAndScore> call, Throwable t) {

            }
        });
    }


    private class DseScoreAdapter extends RecyclerView.Adapter<DSEScoreViewHolder> {

        List<DSEResultAndScore> resultAndScore;

        public DseScoreAdapter(List<DSEResultAndScore> dseResultAndScoreList) {
            resultAndScore = dseResultAndScoreList;
        }

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

        @Override
        public void onBindViewHolder(@NonNull DSEScoreViewHolder holder, int position) {
            double totalValue = 0;
            holder.training_title.setText(resultAndScore.get(position).getTitle());
            holder.training_dates.setText(resultAndScore.get(position).getStartDate() + " - " + resultAndScore.get(position).getEndDate());
            holder.venue.setText(resultAndScore.get(position).getVenueAddress());

            holder.training_id.setText(resultAndScore.get(position).getTrainingId());

            if (resultAndScore.get(position).getPreTestPercentage() != null && !resultAndScore.get(position).getPreTestPercentage().isEmpty()) {
                holder.pre_test_Score.setText(resultAndScore.get(position).getPreTestPercentage());
                totalValue = totalValue + Double.parseDouble(resultAndScore.get(position).getPreTestPercentage());
            }
            if (resultAndScore.get(position).getPostTestPercentage() != null && !resultAndScore.get(position).getPostTestPercentage().isEmpty()) {
                holder.post_test_score.setText(resultAndScore.get(position).getPostTestPercentage());
                totalValue = totalValue + Double.parseDouble(resultAndScore.get(position).getPostTestPercentage());
            }
            if (resultAndScore.get(position).getRoleplayOrDemo() != null && !resultAndScore.get(position).getRoleplayOrDemo().isEmpty()) {
                holder.txtRolePlay.setText(resultAndScore.get(position).getRoleplayOrDemo());
                totalValue = totalValue + Double.parseDouble(resultAndScore.get(position).getRoleplayOrDemo());
            }
            if (resultAndScore.get(position).getPerformance() != null && !resultAndScore.get(position).getPerformance().isEmpty()) {
                holder.txtPerformance.setText(resultAndScore.get(position).getPerformance());
                totalValue = totalValue + Double.parseDouble(resultAndScore.get(position).getPerformance());
            }
            if (resultAndScore.get(position).getAssignment() != null && !resultAndScore.get(position).getAssignment().isEmpty()) {
                holder.txtAssignment.setText(resultAndScore.get(position).getAssignment());
                totalValue = totalValue + Double.parseDouble(resultAndScore.get(position).getAssignment());
            }

            holder.overall_score.setText(String.valueOf(totalValue));
            if (resultAndScore.get(position).getCertification().equalsIgnoreCase("0")) {
                holder.btnCertification.setText("Failed");
                holder.btnCertification.setBackgroundColor(getResources().getColor(R.color.red));
            } else {
                holder.btnCertification.setText("Certified");
                holder.btnCertification.setBackgroundColor(getResources().getColor(R.color.green));
            }

        }

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

    private static class DSEScoreViewHolder extends RecyclerView.ViewHolder {

        TextView training_title, training_dates, venue, pre_test_Score, post_test_score, txtRolePlay, txtAssignment, txtPerformance, activity_score, overall_score, training_id;
        Button btnCertification;


        public DSEScoreViewHolder(@NonNull View itemView) {
            super(itemView);
            training_title = itemView.findViewById(R.id.training_title);
            training_dates = itemView.findViewById(R.id.training_dates);
            venue = itemView.findViewById(R.id.venue);
            pre_test_Score = itemView.findViewById(R.id.pre_test_Score);
            post_test_score = itemView.findViewById(R.id.post_test_score);
            activity_score = itemView.findViewById(R.id.activity_score);
            overall_score = itemView.findViewById(R.id.overall_score);
            training_id = itemView.findViewById(R.id.training_id);
            txtRolePlay = itemView.findViewById(R.id.tct_roleplay);
            txtAssignment = itemView.findViewById(R.id.txt_assignment);
            txtPerformance = itemView.findViewById(R.id.txt_performance);

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


        }
    }
}
