package com.androiddev.project.ili.wishurgift.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.volley.Response;
import com.androiddev.project.ili.wishurgift.R;
import com.androiddev.project.ili.wishurgift.activities.AppMainActivity;
import com.androiddev.project.ili.wishurgift.activities.LoginActivity;
import com.androiddev.project.ili.wishurgift.api.CommentApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.Commentaire;

import java.util.List;

/**
 * Adapter permettant l'affichage et la gestion de commentaires
 */
public class CommentaireAdapter extends ArrayAdapter<Commentaire> {
    private int idParent;
    private int idElement;
    private boolean appartient;


    public CommentaireAdapter(Context context, List<Commentaire> listes) {
        super(context, 0, listes);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_list_comment, parent, false);
        }
        final View listItem = convertView;
        final Commentaire commentaire = getItem(position);
        TextView nom = listItem.findViewById(R.id.nomUserComment);
        TextView date = listItem.findViewById(R.id.dateUserComment);
        TextView texte = listItem.findViewById(R.id.textUserComment);

        Button update = listItem.findViewById(R.id.updateButtonComment);
        nom.setText(commentaire.getUser().getUserName());
        date.setText(commentaire.getDate());
        texte.setText(commentaire.getText());

        Button updateComment = listItem.findViewById(R.id.saveNewComment);
        if(commentaire.getUser().getTag().equals(Wishurgift.getSessionVariables().getUserConnected().getTag())) {
            update.setVisibility(View.VISIBLE);
            update.setOnClickListener(v -> {
                update.setVisibility(View.GONE);
                updateComment.setVisibility(View.VISIBLE);
                texte.setFocusable(true);
                texte.setEnabled(true);
                texte.setClickable(true);
                texte.setFocusableInTouchMode(true);

                updateComment.setOnClickListener(v1 -> editComment(commentaire.getId(), texte.getText().toString()));
            });
        } else {
            update.setVisibility(View.GONE);
        }
        /**
         * Appel api pour supprimer un commentaire
         */
        Log.d("tag",commentaire.getUser().getTag() + " " + Wishurgift.getSessionVariables().getUserConnected().getTag());
        if(commentaire.getUser().getTag().equals(Wishurgift.getSessionVariables().getUserConnected().getTag())) {
            listItem.findViewById(R.id.deleteButtonComment).setVisibility(View.VISIBLE);
            listItem.findViewById(R.id.deleteButtonComment).setOnClickListener(v -> CommentApi.deleteComment(commentaire.getId(), new Response.Listener() {
                @Override
                public void onResponse(Object response) {
                    showElementAfterUpdatingComment(commentaire.getId(), true);
                }
            }, error -> onError()));

        } else {
            listItem.findViewById(R.id.deleteButtonComment).setVisibility(View.GONE);
        }
        return convertView;
    }

    /**
     * Appel api pour éditer un commentaire
     * @param id l'id du commentaire à supprimer
     * @param text le nouveau texte à mettre en place
     */
    public void editComment(int id, String text) {

        CommentApi.updateComment(id, text, response -> showElementAfterDeletingComment(id, true), error -> {
            onError();
        });

    }

    private void showElementAfterDeletingComment(int id, Boolean appartient) {
        ((AppMainActivity) getContext()).afficherElement(idParent, idElement, appartient);
    }



    private void showElementAfterUpdatingComment(int id, Boolean appartient) {
        ((AppMainActivity) getContext()).afficherElement(idParent, idElement, appartient);
    }

    public boolean isAppartient() {
        return appartient;
    }

    public void setAppartient(boolean appartient) {
        this.appartient = appartient;
    }

    public int getIdParent() {
        return idParent;
    }

    public void setIdParent(int idParent) {
        this.idParent = idParent;
    }

    public int getIdElement() {
        return idElement;
    }

    public void setIdElement(int idElement) {
        this.idElement = idElement;
    }

    public void onError(){
        AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("An error has occured");
        alertDialogBuilder.setMessage("You will be redirected to the login page").setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                Wishurgift.getSessionVariables().setUserConnected(null);
                Wishurgift.getSessionVariables().setToken(null);
                ((AppMainActivity)getContext()).finish();
                getContext().startActivity(new Intent(getContext(), LoginActivity.class));
            }
        });
        AlertDialog alertDialog =alertDialogBuilder.create();
        alertDialog.show();
    }
}
