package com.cygnusa.hyperm.adapter;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.github.siyamed.shapeimageview.CircularImageView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.AssessmentActivity;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.PositionUpdateListener;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.AssessmentList;
import com.cygnusa.hyperm.wrappers.ErrorResponse;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import retrofit2.Call;

public class AssessmentListAdapter extends RecyclerView.Adapter<AssessmentListAdapter.ViewHolder> {

    private ArrayList<AssessmentList> ONLINE_ASSESSMENT_LIST;
    private Context context;
    private String TRAINING_ID = "";
    private String CATEGORY_ID = "";
    private PositionUpdateListener listener;
    private ApiService restService;
    private TransparentProgressDialog progressDialog;
    private ArrayList<AssessmentList> OFFLINE_ASSESSMENT_LIST = new ArrayList<>();
    private boolean isOffline;


    public AssessmentListAdapter(Context context, ArrayList<AssessmentList> items,
                                 String id, PositionUpdateListener l, ApiService restService,
                                 boolean isOffline, ArrayList<AssessmentList> assessmentLists) {
        this.ONLINE_ASSESSMENT_LIST = items;
        this.context = context;
        this.TRAINING_ID = id;
        this.listener = l;
        this.restService = restService;

        this.isOffline = isOffline;
        this.OFFLINE_ASSESSMENT_LIST = assessmentLists;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        AssessmentList item;
        if (isOffline) {
            item = OFFLINE_ASSESSMENT_LIST.get(position);
        } else {
            item = ONLINE_ASSESSMENT_LIST.get(position);
        }

        holder.view.setTag(item);
        holder.assesmentTitle.setSelected(true);
        holder.assesmentTitle.setText(item.getAssessmentname());
        holder.publishedDate.setText("Published On: " + dateFormate(item.getPublisheddate()));

        if (item.getStatus().equalsIgnoreCase("1")) {
            holder.assesmentStatue.setText(item.getStatusname());
        } else if (item.getStatus().equalsIgnoreCase("3")) {
            holder.assesmentStatue.setText(item.getStatusname() + " On: " + dateFormate(item.getCompleted_time()));

        } else if (item.getStatus().equalsIgnoreCase("7")) {
            holder.assesmentStatue.setText(item.getStatusname());
        } else {
            holder.assesmentStatue.setText(item.getStatusname());
        }


        if (item.getAtype().equalsIgnoreCase("0")) {
            holder.assessmentType.setText("Learning");
            holder.image.setImageResource(R.mipmap.assessmenttype_2);
        } else {
            holder.assessmentType.setText("Certification");
            holder.image.setImageResource(R.mipmap.assessmenttype_1);
        }


        int d = (int) Math.round(Double.parseDouble(item.getHighscore().trim()));
        holder.score.setText(String.valueOf(d));

        if (item.getStatus().trim().equalsIgnoreCase("7")) {
            holder.scoreLayout.setBackgroundColor(Color.parseColor("#B5B5B5"));
            holder.assesmentStatue.setTextColor(Color.parseColor("#B5B5B5"));
        } else {
            if (d >= 80) {
                holder.scoreLayout.setBackgroundColor(Color.parseColor("#1D7210"));
                // holder.assesmentStatue.setTextColor(Color.parseColor("#1D7210"));
            } else {
                holder.scoreLayout.setBackgroundColor(context.getResources().getColor(R.color.material_red900));
                // holder.assesmentStatue.setTextColor(Color.parseColor("#F7412D"));
            }
        }

        if (item.getStatus().trim().equalsIgnoreCase("3")) {
            //holder.assesmentStatue.setTextColor(Color.parseColor("#1D7210"));
        }


        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AssessmentList assessmentList = (AssessmentList) v.getTag();
                if (isOffline) {
                    Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_answer where assessment_id='"
                            + assessmentList.getAssessmentid()
                            + "' and category_id='" + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'", null);
                    if (cursor.getCount() == 0) {
                        if (Integer.parseInt(assessmentList.getAttemptslimit().trim())
                                > assessmentList.getAttempt_time()) {
                            if (assessmentList.getIs_expired().trim().equalsIgnoreCase("0")) {
                                AssessmentActivity.ASSESSMENT = assessmentList;
                                AssessmentActivity.TRAINING_ID = TRAINING_ID;
                                AssessmentActivity.CATEGORY_ID = CATEGORY_ID;
                                AssessmentActivity.isOffline = isOffline;
                                if (listener != null) {
                                    listener.onPositionUpdate(OFFLINE_ASSESSMENT_LIST.indexOf(assessmentList));
                                }
                                context.startActivity(new Intent(context, AssessmentActivity.class));
                            } else {
                                GlobalData.showToast(context,
                                        "Assessment expired", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            GlobalData.showToast(context, "You have attempted this test "
                                    + assessmentList.getAttempt_time() + " times. Please contact the admin for more details.", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        GlobalData.showToast(context, "You are not allowed to made more than 1 attempt when offline", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_answer where assessment_id='"
                            + assessmentList.getAssessmentid()
                            + "' and category_id='" + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'", null);
                    if (cursor.getCount() == 0) {
                        if (Integer.parseInt(assessmentList.getAttemptslimit().trim())
                                > assessmentList.getAttempt_time()) {
                            if (assessmentList.getIs_expired().trim().equalsIgnoreCase("0")) {
                                Cursor cursor1 = GlobalData.sdb.rawQuery("select * from assessment_question where category_id='"
                                        + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "' and assessment_id='"
                                        + assessmentList.getAssessmentid() + "'", null);

                                if (cursor1.getCount() > 0 || new UtilService().isNetworkAvailable(context)) {
                                    AssessmentActivity.ASSESSMENT = assessmentList;
                                    AssessmentActivity.TRAINING_ID = TRAINING_ID;
                                    AssessmentActivity.CATEGORY_ID = CATEGORY_ID;
                                    AssessmentActivity.isOffline = isOffline;
                                    if (listener != null) {
                                        listener.onPositionUpdate(ONLINE_ASSESSMENT_LIST.indexOf(assessmentList));
                                    }
                                    context.startActivity(new Intent(context, AssessmentActivity.class));
                                } else {
                                    GlobalData.showToast(context,
                                            "Please check your internet connection", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                GlobalData.showToast(context,
                                        "Assessment expired", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            GlobalData.showToast(context, "You have attempted this test "
                                    + assessmentList.getAttempt_time() + " times. Please contact the admin for more details.", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        GlobalData.showToast(context, "You are not allowed to made more than 1 attempt when offline", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

//        holder.errorImage.setId(position);
//        holder.errorImage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String str = (String) v.getTag();
//                str = str == null ? "" : str;
//                Tooltip.TooltipView tooltip = Tooltip.make(context,
//                        new Tooltip.Builder(101)
//                                .anchor(v, Tooltip.Gravity.LEFT)
//                                .closePolicy(new Tooltip.ClosePolicy()
//                                        .insidePolicy(true, false)
//                                        .outsidePolicy(true, false), 5000)
//                                .activateDelay(800)
//                                .withStyleId(R.style.ToolTipLayoutCustomStyle)
//                                .showDelay(300)
//                                .text(str)
//                                .maxWidth(500)
//                                .withArrow(true)
//                                .withOverlay(true)
//                                .floatingAnimation(Tooltip.AnimationBuilder.DEFAULT)
//                                .build()
//                );
//                tooltip.setTextColor(Color.WHITE);
//                tooltip.show();
//            }
//        });

    }


    public String dateFormate(String dte) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = null;
        try {
            newDate = format.parse(dte);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        format = new SimpleDateFormat("dd-MMM-yyyy");
        String date = format.format(newDate);


        return date;
    }

    private void updateLocalAssessment(int id) {
        if (new UtilService().isNetworkAvailable(context)) {
            Cursor cursor1 = GlobalData.sdb.rawQuery("select * from assessment_answer where assessment_id='"
                    + ONLINE_ASSESSMENT_LIST.get(id).getAssessmentid()
                    + "' and category_id='" + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'", null);
            if (cursor1.getCount() != 0) {
                cursor1.moveToFirst();
                Gson gson = new Gson();
                HashMap<String, String> map = gson.fromJson(
                        cursor1.getString(cursor1.getColumnIndex("assessment_answer")),
                        new TypeToken<HashMap<String, String>>() {
                        }.getType());
                progressDialog = new TransparentProgressDialog(context);
                progressDialog.show();

                restService.postAssessment(cursor1.getString(cursor1.getColumnIndex("assessment_id")), map)
                        .enqueue(new MyCallback<AnswerResponse>(cursor1.getInt(cursor1.getColumnIndex("id"))) {
                            @Override
                            public void onResponse(Call<AnswerResponse> call, retrofit2.Response<AnswerResponse> response) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                if (response.body() != null && response.body().getStatus() == 200) {
                                    Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_answer where id=" + id, null);
                                    if (cursor.getCount() > 0) {
                                        cursor.moveToFirst();
                                        GlobalData.sdb.execSQL("delete from assessment_question where assessment_id='"
                                                + cursor.getString(cursor.getColumnIndex("assessment_id"))
                                                + "' and category_id='" + cursor.getString(cursor.getColumnIndex("category_id"))
                                                + "' and training_id='" + cursor.getString(cursor.getColumnIndex("training_id")) + "'");

                                        GlobalData.sdb.execSQL("delete from assessment where assessment_id='"
                                                + cursor.getString(cursor.getColumnIndex("assessment_id"))
                                                + "' and category_id='" + cursor.getString(cursor.getColumnIndex("category_id"))
                                                + "' and training_id='" + cursor.getString(cursor.getColumnIndex("training_id")) + "'");

                                        GlobalData.sdb.execSQL("delete from assessment_answer where id=" + id);
                                    }
                                    try {
                                        ONLINE_ASSESSMENT_LIST.get(id).setHighscore(response.body()
                                                .getData().getPercentage_score());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                } else if (response.body() != null && response.body().getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                } else if (response.body() != null) {
                                    GlobalData.sdb.execSQL("update assessment_answer set error='"
                                            + response.body().getMessage() + "' where id=" + id);
                                } else if (response.errorBody() != null) {
                                    Gson gson = new Gson();
                                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                    GlobalData.sdb.execSQL("update assessment_answer set error='"
                                            + message.getMessage() + "' where id=" + id);
                                    if (message.getStatus() == 401) {
                                        GlobalData.canLogout = true;
                                        new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                    }
                                }
                                notifyDataSetChanged();
                            }

                            @Override
                            public void onFailure(Call<AnswerResponse> call, Throwable t) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                GlobalData.showToast(context, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                            }
                        });
            } else {
                GlobalData.showToast(context, "No local assessment found", Toast.LENGTH_SHORT).show();
            }
        } else {
            GlobalData.showToast(context, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getItemCount() {
        if (isOffline) {
            return OFFLINE_ASSESSMENT_LIST.size();
        } else {
            return ONLINE_ASSESSMENT_LIST.size();
        }
    }

    public void add(AssessmentList item, int position) {
        if (isOffline) {
            OFFLINE_ASSESSMENT_LIST.add(position, item);
        } else {
            ONLINE_ASSESSMENT_LIST.add(position, item);
        }
        notifyItemInserted(position);
    }

    public void add(AssessmentList item) {
        if (isOffline) {
            OFFLINE_ASSESSMENT_LIST.add(item);
            notifyItemInserted(OFFLINE_ASSESSMENT_LIST.size());
        } else {
            ONLINE_ASSESSMENT_LIST.add(item);
            notifyItemInserted(ONLINE_ASSESSMENT_LIST.size());
        }
    }

    public void remove(int position) {
        if (isOffline) {
            OFFLINE_ASSESSMENT_LIST.remove(position);
        } else {
            ONLINE_ASSESSMENT_LIST.remove(position);
        }
        notifyItemRemoved(position);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout scoreLayout;
        TextView assesmentTitle, assesmentStatue, score, assessmentType, publishedDate, completedDate;
        View view;
        ImageView errorImage;
        CircularImageView image;

        private ViewHolder(View itemView) {
            super(itemView);
            view = itemView;

            scoreLayout = itemView.findViewById(R.id.scoreLayout);
            assesmentTitle = itemView.findViewById(R.id.assessment_title);
            image = itemView.findViewById(R.id.image);
            assesmentStatue = itemView.findViewById(R.id.completedDate);
            publishedDate = itemView.findViewById(R.id.publishedDate);
            completedDate = itemView.findViewById(R.id.completedDate);
            score = itemView.findViewById(R.id.score);
            assessmentType = itemView.findViewById(R.id.assessment_type);
            // errorImage = itemView.findViewById(R.id.errorImage);
        }

    }
}
