package app.fedilab.fedilabtube.drawer;
/* Copyright 2020 Thomas Schneider
 *
 * This file is a part of TubeLab
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with TubeLab; if not,
 * see <http://www.gnu.org/licenses>. */

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.CommentData.Comment;
import app.fedilab.fedilabtube.client.entities.Report;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.viewmodel.PostActionsVM;
import es.dmoral.toasty.Toasty;


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


    public AllCommentRemoved allCommentRemoved;
    private Context context;
    private List<Comment> comments;
    private CommentListAdapter commentListAdapter;

    public CommentListAdapter(List<Comment> comments) {
        this.comments = comments;
        commentListAdapter = this;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

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


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        context = parent.getContext();
        LayoutInflater layoutInflater = LayoutInflater.from(this.context);
        return new ViewHolder(layoutInflater.inflate(R.layout.drawer_comment, parent, false));
    }

    @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) {

        context = viewHolder.itemView.getContext();

        final ViewHolder holder = (ViewHolder) viewHolder;

        final Comment comment = comments.get(i);


        if (comment == null)
            return;


        holder.more_actions.setOnClickListener(view -> {
            PopupMenu popup = new PopupMenu(context, holder.more_actions);
            popup.getMenuInflater()
                    .inflate(R.menu.comment_menu, popup.getMenu());
            if (!Helper.isOwner(context, comment.getAccount())) {
                popup.getMenu().findItem(R.id.action_delete).setVisible(false);
            }
            popup.setOnMenuItemClickListener(item -> {
                switch (item.getItemId()) {
                    case R.id.action_delete:
                        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
                        builder.setTitle(R.string.delete_comment);
                        builder.setMessage(R.string.delete_comment_confirm);
                        builder.setIcon(android.R.drawable.ic_dialog_alert)
                                .setPositiveButton(R.string.delete, (dialog, which) -> {
                                    new Thread(() -> {
                                        new RetrofitPeertubeAPI(context).post(RetrofitPeertubeAPI.ActionType.PEERTUBEDELETECOMMENT, comment.getVideoId(), comment.getId());
                                        Handler mainHandler = new Handler(Looper.getMainLooper());
                                        Runnable myRunnable = () -> {
                                            comments.remove(comment);
                                            notifyDataSetChanged();
                                            if (comments.size() == 0) {
                                                allCommentRemoved.onAllCommentRemoved();
                                            }
                                        };
                                        mainHandler.post(myRunnable);
                                    }).start();

                                    dialog.dismiss();
                                })
                                .setNegativeButton(R.string.no, (dialog, which) -> dialog.dismiss())
                                .show();
                        break;
                    case R.id.action_report:
                        reportComment(comment);
                        break;
                }
                return true;
            });
            popup.show();
        });
        holder.comment_content.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP && !view.hasFocus()) {
                try {
                    view.requestFocus();
                } catch (Exception ignored) {
                }
            }
            return false;
        });

        Spanned commentSpan;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            commentSpan = Html.fromHtml(comment.getText(), Html.FROM_HTML_MODE_LEGACY);
        else
            commentSpan = Html.fromHtml(comment.getText());
        holder.comment_content.setText(commentSpan, TextView.BufferType.SPANNABLE);

        holder.comment_content.setMovementMethod(LinkMovementMethod.getInstance());

        holder.comment_account_displayname.setText(comment.getAccount().getDisplayName());

        if (comment.getAccount() != null) {
            Spannable wordtoSpan;
            Pattern hashAcct;
            wordtoSpan = new SpannableString("@" + comment.getAccount().getAcct());
            hashAcct = Pattern.compile("(@" + comment.getAccount().getAcct() + ")");
            Matcher matcherAcct = hashAcct.matcher(wordtoSpan);
            while (matcherAcct.find()) {
                int matchStart = matcherAcct.start(1);
                int matchEnd = matcherAcct.end();
                if (wordtoSpan.length() >= matchEnd && matchStart < matchEnd) {
                    wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, android.R.color.darker_gray)), matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                }
            }
            holder.comment_account_username.setText(wordtoSpan);
        }

        holder.comment_date.setText(Helper.dateDiff(context, comment.getCreatedAt()));


        Helper.loadGiF(context, comment.getAccount().getAvatar() != null ? comment.getAccount().getAvatar().getPath() : null, holder.comment_account_profile);
    }

    public void manageVIewPostActions(RetrofitPeertubeAPI.ActionType statusAction, APIResponse apiResponse) {

        if (apiResponse.getError() != null) {
            Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
            return;
        }
        if (statusAction == RetrofitPeertubeAPI.ActionType.PEERTUBEDELETECOMMENT) {
            int position = 0;
            for (Comment comment : comments) {
                if (comment.getId().equals(apiResponse.getTargetedId())) {
                    comments.remove(comment);
                    commentListAdapter.notifyItemRemoved(position);
                    break;
                }
                position++;
            }
        } else if (statusAction == RetrofitPeertubeAPI.ActionType.REPORT_COMMENT) {
            Toasty.success(context, context.getString(R.string.successful_report_comment), Toasty.LENGTH_LONG).show();
        }
    }


    private void reportComment(Comment comment) {
        androidx.appcompat.app.AlertDialog.Builder dialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(context);
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.popup_report, new LinearLayout(context), false);
        dialogBuilder.setView(dialogView);
        EditText report_content = dialogView.findViewById(R.id.report_content);
        dialogBuilder.setNeutralButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
        dialogBuilder.setPositiveButton(R.string.report, (dialog, id) -> {
            if (report_content.getText().toString().trim().length() == 0) {
                Toasty.info(context, context.getString(R.string.report_comment_size), Toasty.LENGTH_LONG).show();
            } else {
                PostActionsVM viewModel = new ViewModelProvider((ViewModelStoreOwner) context).get(PostActionsVM.class);
                Report report = new Report();
                Report.CommentReport commentReport = new Report.CommentReport();
                commentReport.setId(comment.getId());
                report.setComment(commentReport);
                report.setReason(report_content.getText().toString());
                viewModel.report(report).observe((LifecycleOwner) context, apiResponse -> manageVIewPostActions(RetrofitPeertubeAPI.ActionType.REPORT_COMMENT, apiResponse));
                dialog.dismiss();
            }
        });
        androidx.appcompat.app.AlertDialog alertDialog2 = dialogBuilder.create();
        alertDialog2.show();
    }

    public interface AllCommentRemoved {
        void onAllCommentRemoved();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView comment_content;
        TextView comment_account_username;
        TextView comment_account_displayname;
        ImageView comment_account_profile;
        TextView comment_date;
        LinearLayout main_container;
        TextView more_actions;

        @SuppressLint("SetJavaScriptEnabled")
        ViewHolder(View itemView) {
            super(itemView);
            comment_content = itemView.findViewById(R.id.comment_content);
            comment_account_username = itemView.findViewById(R.id.comment_account_username);
            comment_account_profile = itemView.findViewById(R.id.comment_account_profile);
            comment_account_displayname = itemView.findViewById(R.id.comment_account_displayname);
            comment_date = itemView.findViewById(R.id.comment_date);
            main_container = itemView.findViewById(R.id.main_container);
            more_actions = itemView.findViewById(R.id.more_actions);

        }

        public View getView() {
            return itemView;
        }


    }

}