package kz.arta.synergy.workflow.mobile.android.comments.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
import com.google.gson.JsonSyntaxException;

import java.util.ArrayList;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.comments.CommentConst;
import kz.arta.synergy.workflow.mobile.android.comments.models.AllCommentsItem;
import kz.arta.synergy.workflow.mobile.android.comments.models.CommentItem;
import kz.arta.synergy.workflow.mobile.android.common.ActivityConst;
import kz.arta.synergy.workflow.mobile.android.common.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.models.ErrorCode;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.models.User;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineComment;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddComment;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddRemoveComment;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorkCommentsTable;
import kz.arta.synergy.workflow.mobile.android.common.requests.RestClient;
import kz.arta.synergy.workflow.mobile.android.common.requests.SendGetRequest;
import kz.arta.synergy.workflow.mobile.android.common.utils.ActionUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.DateUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Wrapper;
import kz.arta.synergy.workflow.mobile.android.documents.common.models.DocumentItem;
import kz.arta.synergy.workflow.mobile.android.documents.offline.DocumentCommentsTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentAddCommentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentRemoveCommentTable;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

/**
 * Created by neox on 21.07.14.
 * Неполный список комментариев
 */
public class CommentsList extends AsyncTask<Void, Void, AllCommentsItem> {

    /**
     * startActivityForResult
     */
    private static final int COMMENT = 1;
    /**
     * Тип комментариев
     */
    public static String commentType = CommentConst.WORK;
    /**
     * Данные для авторизированного пользователя
     */
    private Person person;
    /**
     * Активити
     */
    private Activity activity;
    /**
     * Настройки
     */
    private SharedPreferences settings;
    /**
     * Работа
     */
    private WorkItem work;
    /**
     * Документ
     */
    private DocumentItem document;
    /**
     * Список комментариев (для оффлайн режима)
     */
    private List<CommentItem> offlineComments;
    /**
     * Список комментариев
     */
    private AllCommentsItem currentComments;
    /**
     * UUID выделенного комментария (используется при редактировании/изменении)
     */
    private String commentID;
    /**
     * Текст выделенного комментария
     */
    private String commentName;
    /**
     * id выделенного комментария
     */
    private int commentTag;
    /**
     * UUID работы (используется в случае если добавляется комментарий для документа который содержит работу)
     */
    private String workID;
    /**
     * Кнопка для загрузки комментариев для работы
     */
    private Button workButton;

    /**
     * Кнопка для загрузки комментариев для документа
     */
    private Button documentButton;

    /**
     * Кнопка для загрузки личных комментариев
     */
    private Button personalButton;

    public CommentsList(Activity activity, Person person, WorkItem work,
                        Button workButton, Button documentButton, Button personalButton) {
        this.work = work;
        this.workButton = workButton;
        this.documentButton = documentButton;
        this.personalButton = personalButton;
        init(activity, person);
    }

    public CommentsList(Activity activity, Person person, DocumentItem document, String workID,
                        Button workButton, Button documentButton, Button personalButton) {
        this.document = document;
        this.workID = workID;
        this.workButton = workButton;
        this.documentButton = documentButton;
        this.personalButton = personalButton;
        init(activity, person);
    }

    private void init(Activity activity, Person person) {
        this.activity = activity;
        this.person = person;
        settings = activity.getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);
        initButtons();
    }

    /**
     * Инициализация кнопок
     */
    private void initButtons() {
        switch (commentType) {
            case CommentConst.WORK:
                workButton.setBackgroundResource(R.drawable.comments_button_left_selected);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                break;
            case CommentConst.DOCUMENT:
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center_selected);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                break;
            case CommentConst.PERSONAL:
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right_selected);
                break;
        }
    }

    @Override
    protected void onPostExecute(final AllCommentsItem comments) {

        LayoutInflater ltInflater = activity.getLayoutInflater();

        currentComments = comments;

        // это леяут с комментариями
        LinearLayout commentsLayout = (LinearLayout) activity.findViewById(R.id.comments);
        commentsLayout.removeAllViews();

        // а это наша кнопка "перейти к комментариям"
        RelativeLayout goToComments = (RelativeLayout) activity.findViewById(R.id.go_to_comments_button);
        goToComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, AllCommentsActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                if (work != null) {
                    intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                    intent.putExtra(ActivityConst.WORK_NAME, work.getName());
                }
                if (workID != null) {
                    intent.putExtra(ActivityConst.WORK_ID, workID);
                }
                if (document != null) {
                    intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
                    intent.putExtra(ActivityConst.WORK_NAME, document.getName());
                }
                intent.putExtra(ActivityConst.COMMENT_TYPE, commentType);
                activity.startActivityForResult(intent, ActionUtils.COMMENT);
            }
        });

        ((TextView) activity.findViewById(R.id.go_to_comments_label)).setTypeface(Fonts.getMedium(activity));

        TextView commentsCount = (TextView) activity.findViewById(R.id.go_to_comments_count_label);
        commentsCount.setTypeface(Fonts.getMedium(activity));

        if (currentComments != null) {
            if (currentComments.getList().length != 0) {
                // количество комментариев
                commentsCount.setText(currentComments.getCount());
                // добавляем комменты
                for (int countComments = 0; countComments < currentComments.getList().length; countComments++) {
                    showItemComments(commentsLayout, ltInflater, currentComments, countComments);
                }
                // включаем комментарии и кнопку
                showComments(commentsLayout);
            } else {
                commentsCount.setText(Wrapper.NO_ERROR);
                // если ничего не найдено отключаем
                hideComments(commentsLayout);
            }
        } else {
            if (Utils.checkSyncEnables(settings)) {

                offlineComments = new ArrayList<>();
                List<OfflineComment> addedComments = new ArrayList<>();
                List<CommentItem> commentItemList = new ArrayList<>();

                if (work != null || workID != null) { // комментарии для работы из модуля работы
                    if (work == null) {
                        work = new WorkItem();
                        work.setActionID(workID);
                    }
                    // добавленные оффлайн комментарии
                    addedComments = new AddComment(activity).getByWorkIDAndType(work.getActionID(), commentType);
                    // синхронизированные комментарии
                    commentItemList = new WorkCommentsTable(activity.getBaseContext()).getByWorkIDAndType(work.getActionID(), commentType);
                } else if (document != null) { // комментарии для документа из модуля документы
                    // добавленные оффлайн комментарии
                    addedComments = new DocumentAddCommentTable(activity).getByDocumentID(document.getDocumentID());
                    // синхронизированные комментарии
                    commentItemList = new DocumentCommentsTable(activity.getBaseContext()).get(document.getDocumentID());
                }

                for (OfflineComment addedComment : addedComments) {
                    User author = new User();
                    author.setName(addedComment.getAuthor());
                    CommentItem comment = new CommentItem();
                    comment.setComment(addedComment.getComment());
                    comment.setAuthor(author);
                    comment.setCreated_label(DateUtils.parseDateOfflineComment(Long.parseLong(addedComment.getTime()), activity));
                    comment.setIs_editable("true");
                    comment.setIs_deletable("true");
                    comment.setType(addedComment.getType());
                    comment.setComment_icon_type(addedComment.getType().equals(CommentConst.PERSONAL) ? "comment_icon_blue" : "comment_icon");
                    offlineComments.add(comment);
                }

                for (CommentItem comment : commentItemList) {
                    offlineComments.add(comment);
                }

                // если комменты есть
                if (!offlineComments.isEmpty()) {
                    // количество комментариев
                    commentsCount.setText(String.valueOf(offlineComments.size()));
                    // добавляем комментарии
                    if (offlineComments.size() <= 3) {
                        for (int i = 0; i < offlineComments.size(); i++) {
                            showItemCommentsOffline(commentsLayout, ltInflater, offlineComments.get(i), i);
                        }
                    } else {
                        for (int i = 0; i < 3; i++) {
                            showItemCommentsOffline(commentsLayout, ltInflater, offlineComments.get(i), i);
                        }
                    }
                    // отображаем комментарии и кнопку
                    showComments(commentsLayout);
                } else {
                    commentsCount.setText(Wrapper.NO_ERROR);
                    // если ничего не найдено отключаем
                    hideComments(commentsLayout);
                }
            }
        }
        super.onPostExecute(comments);
    }


    private void showItemComments(LinearLayout commentsLayout, LayoutInflater ltInflater, final AllCommentsItem comment, int i) {

        View item = ltInflater.inflate(R.layout.item_comments, commentsLayout, false);

        if (item != null) {

            item.setOnTouchListener(new OnSwipeTouchListener() {

                public void onSwipeRight() {
                    swipeRight();
                    getComments();
                }

                public void onSwipeLeft() {
                    swipeLeft();
                    getComments();
                }

                @Override
                public void onFuckingLong(View view) {
                    commentTag = Integer.parseInt(view.getTag().toString());
                    commentID = comment.getList()[commentTag].getCommentID();
                    commentName = comment.getList()[commentTag].getComment();
                    showCommentDialog();
                    super.onFuckingLong(view);
                }
            });

            ImageView commentIcon = (ImageView) item.findViewById(R.id.info_work_comment_icon);

            switch (comment.getList()[i].getComment_icon_type()) {
                case CommentConst.COMMENT_ICON:
                    commentIcon.setImageResource(R.drawable.comment_icon);
                    break;
                case CommentConst.COMMENT_ICON_GRAY:
                    commentIcon.setImageResource(R.drawable.comment_icon_gray);
                    break;
                case CommentConst.COMMENT_ICON_GREEN:
                    commentIcon.setImageResource(R.drawable.comment_icon_green);
                    break;
                case CommentConst.COMMENT_ICON_RED:
                    commentIcon.setImageResource(R.drawable.comment_icon_red);
                    break;
                case CommentConst.COMMENT_ICON_RESULT:
                    commentIcon.setImageResource(R.drawable.comment_icon_result);
                    break;
                case CommentConst.COMMENT_ICON_BLUE:
                    commentIcon.setImageResource(R.drawable.comment_icon_blue);
                    break;
            }

            TextView commentAuthor = (TextView) item.findViewById(R.id.info_work_comment_name);
            commentAuthor.setText(comment.getList()[i].getAuthor().name);
            commentAuthor.setTypeface(Fonts.getMedium(activity));

            TextView commentText = (TextView) item.findViewById(R.id.info_work_comment_text);
            commentText.setText(comment.getList()[i].getComment());
            commentText.setTypeface(Fonts.getRoman(activity));

            TextView commentData = (TextView) item.findViewById(R.id.info_work_comment_time);
            commentData.setText(comment.getList()[i].getCreated_label());
            commentData.setTypeface(Fonts.getMedium(activity));

            item.setTag(i);

            commentsLayout.addView(item);
        }
    }

    /**
     * Обновление кнопок при свайпе вправо
     */
    private void swipeRight() {
        switch (commentType) {
            case CommentConst.WORK:
                workButton.setBackgroundResource(R.drawable.comments_button_left_selected);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                commentType = CommentConst.WORK;
                break;
            case CommentConst.DOCUMENT:
                workButton.setBackgroundResource(R.drawable.comments_button_left_selected);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                commentType = CommentConst.WORK;
                break;
            case CommentConst.PERSONAL:
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center_selected);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                commentType = CommentConst.DOCUMENT;
                break;
        }
    }

    /**
     * Обновление кнопок при свайпе влево
     */
    private void swipeLeft() {
        switch (commentType) {
            case CommentConst.WORK:
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center_selected);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                commentType = CommentConst.DOCUMENT;
                break;
            case CommentConst.DOCUMENT:
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right_selected);
                commentType = CommentConst.PERSONAL;
                break;
            case CommentConst.PERSONAL:
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right_selected);
                commentType = CommentConst.PERSONAL;
                break;
        }
    }

    private void showItemCommentsOffline(LinearLayout commentsLayout, LayoutInflater ltInflater, CommentItem comment, int i) {

        View item = ltInflater.inflate(R.layout.item_comments, commentsLayout, false);

        if (item != null) {

            item.setOnTouchListener(new OnSwipeTouchListener() {

                public void onSwipeRight() {
                    swipeRight();
                    getComments();
                }

                public void onSwipeLeft() {
                    swipeLeft();
                    getComments();
                }

                @Override
                public void onFuckingLong(View view) {
                    commentTag = Integer.parseInt(view.getTag().toString());
                    commentID = offlineComments.get(commentTag).getCommentID();
                    commentName = offlineComments.get(commentTag).getComment();
                    showCommentDialog();
                    super.onFuckingLong(view);
                }
            });

            ImageView commentIcon = (ImageView) item.findViewById(R.id.info_work_comment_icon);

            switch (comment.getComment_icon_type()) {
                case CommentConst.COMMENT_ICON:
                    commentIcon.setImageResource(R.drawable.comment_icon);
                    break;
                case CommentConst.COMMENT_ICON_GRAY:
                    commentIcon.setImageResource(R.drawable.comment_icon_gray);
                    break;
                case CommentConst.COMMENT_ICON_GREEN:
                    commentIcon.setImageResource(R.drawable.comment_icon_green);
                    break;
                case CommentConst.COMMENT_ICON_RED:
                    commentIcon.setImageResource(R.drawable.comment_icon_red);
                    break;
                case CommentConst.COMMENT_ICON_RESULT:
                    commentIcon.setImageResource(R.drawable.comment_icon_result);
                    break;
                case CommentConst.COMMENT_ICON_BLUE:
                    commentIcon.setImageResource(R.drawable.comment_icon_blue);
                    break;
            }

            TextView commentAuthor = (TextView) item.findViewById(R.id.info_work_comment_name);
            commentAuthor.setText(comment.getAuthor().getName());
            commentAuthor.setTypeface(Fonts.getMedium(activity));

            TextView commentText = (TextView) item.findViewById(R.id.info_work_comment_text);
            commentText.setText(comment.getComment());
            commentText.setTypeface(Fonts.getRoman(activity));

            TextView commentData = (TextView) item.findViewById(R.id.info_work_comment_time);
            commentData.setText(comment.getCreated_label());
            commentData.setTypeface(Fonts.getMedium(activity));

            item.setTag(i);

            commentsLayout.addView(item);
        }
    }

    @Override
    protected AllCommentsItem doInBackground(Void... voids) {
        // тут получаем комменты
        AllCommentsItem allCommentsItem = null;
        String str;
        if (work != null) {
            str = new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/"
                    + work.getActionID() + "/comments?count=3&getCounters=true" + "&locale=" + MyApplication.getLang() + "&type=" + commentType);
        } else {
            if (commentType.equals(CommentConst.DOCUMENT)) {
                str = new SendGetRequest(person).requestGET(person.getHost() + "rest/api/docflow/doc/comments/list?documentID=" +
                        document.getDocumentID() + "&getCounters=true&count=3&locale=" + MyApplication.getLang());
            } else {
                str = new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/"
                        + workID + "/comments?count=3&getCounters=true" + "&locale=" + MyApplication.getLang() + "&type=" + commentType);
            }
        }
        if (str != null) {
            try {
                allCommentsItem = RestClient.getGson().fromJson(str, AllCommentsItem.class);
            } catch (JsonSyntaxException e) {
                return null;
            }
        }
        return allCommentsItem;
    }

    /**
     * Метод вызывается при редактировании комментария
     *
     * @param commentTime время последнего изменения комментария
     */
    private void editCommentIntent(String commentTime) {
        Intent intent = new Intent(activity, AddCommentActivity.class);
        intent.putExtra(ActivityConst.COMMENT_ID, commentID);
        intent.putExtra(ActivityConst.PERSON, person);
        intent.putExtra(ActivityConst.COMMENT_TIME, commentTime);
        intent.putExtra(ActivityConst.COMMENT_TEXT, commentName);
        intent.putExtra(ActivityConst.COMMENT_TYPE, commentType);
        intent.putExtra(ActivityConst.EDIT, true);
        if (workID != null) {
            intent.putExtra(ActivityConst.WORK_ID, workID);
        }
        if (work != null) {
            intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
            intent.putExtra(ActivityConst.WORK_NAME, work.getName());
        }
        if (document != null) {
            intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
            intent.putExtra(ActivityConst.WORK_NAME, document.getName());
        }
        activity.startActivityForResult(intent, COMMENT);
    }

    /**
     * Метод вызывается при долгом нажатии на комментарий
     */
    private void showCommentDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(activity.getString(R.string.edit_comment_title));
        final List<String> items = new ArrayList<>();
        if (Utils.isOnline(activity, person.getHost())) {
            if (currentComments.getList()[commentTag].getIs_editable().equals("true")) {
                items.add(activity.getString(R.string.edit));
            }
            if (currentComments.getList()[commentTag].getIs_deletable().equals("true")) {
                items.add(activity.getString(R.string.delete));
            }
        } else if (Utils.checkSyncEnables(settings)) {
            if (offlineComments.get(commentTag).getIs_editable().equals("true")) {
                items.add(activity.getString(R.string.edit));
            }
            if (offlineComments.get(commentTag).getIs_deletable().equals("true")) {
                items.add(activity.getString(R.string.delete));
            }
        }
        builder.setItems(items.toArray(new String[items.size()]), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items.get(item).equals(activity.getString(R.string.edit))) {
                    if (Utils.isOnline(activity, person.getHost())) {
                        editCommentIntent(currentComments.getList()[commentTag].getCreated_label());
                    } else if (Utils.checkSyncEnables(settings)) {
                        editCommentIntent(offlineComments.get(commentTag).getCreated_label());
                    }
                } else if (items.get(item).equals(activity.getString(R.string.delete))) {
                    if (Utils.isOnline(activity, person.getHost())) {
                        AlertDialog.Builder ad = new AlertDialog.Builder(activity);
                        ad.setTitle(activity.getString(R.string.deleting_comment));
                        ad.setMessage(activity.getString(R.string.are_u_sure_deleting_comment_question) + "?");
                        ad.setPositiveButton(activity.getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                RemoveCommentRequest removeCommentRequest = new RemoveCommentRequest();
                                removeCommentRequest.setCommentID(commentID);
                                removeCommentRequest.execute();
                            }
                        });
                        ad.setNegativeButton(activity.getString(R.string.no), null);
                        ad.show();
                    } else if (Utils.checkSyncEnables(settings)) {
                        if (commentID == null) {
                            AlertDialog.Builder ad = new AlertDialog.Builder(activity);
                            ad.setTitle(activity.getString(R.string.deleting_comment));
                            ad.setMessage(activity.getString(R.string.are_u_sure_deleting_comment_question) + "?");
                            ad.setPositiveButton(activity.getString(R.string.yes), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int arg1) {
                                    if (document != null && work == null) {
                                        DocumentAddCommentTable documentAddCommentTable = new DocumentAddCommentTable(activity.getBaseContext());
                                        documentAddCommentTable.removeCommentByData(offlineComments.get(commentTag).getCreated_label());
                                    } else {
                                        AddComment addComment = new AddComment(activity.getBaseContext());
                                        addComment.removeCommentByData(offlineComments.get(commentTag).getCreated_label());
                                    }
                                    getComments();
                                }
                            });
                            ad.setNegativeButton(activity.getString(R.string.no), null);
                            ad.setCancelable(true);
                            ad.show();
                        } else {
                            AlertDialog.Builder ad = new AlertDialog.Builder(activity);
                            ad.setTitle(activity.getString(R.string.deleting_comment));
                            ad.setMessage(activity.getString(R.string.are_u_sure_deleting_comment_question) + "?");
                            ad.setPositiveButton(activity.getString(R.string.yes), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int arg1) {
                                    if (document != null && work == null) {

                                        DocumentRemoveCommentTable documentRemoveCommentTable = new DocumentRemoveCommentTable(activity.getBaseContext());
                                        documentRemoveCommentTable.add(document.getDocumentID(), commentID, document.getName(), offlineComments.get(commentTag).getComment());

                                        DocumentCommentsTable documentCommentsTable = new DocumentCommentsTable(activity.getBaseContext());
                                        documentCommentsTable.removeCommentByID(commentID);

                                    } else {

                                        AddRemoveComment addRemoveComment = new AddRemoveComment(activity.getBaseContext());
                                        addRemoveComment.add(work.getActionID(), commentID, work.getName(), offlineComments.get(commentTag).getComment());

                                        WorkCommentsTable workCommentsTable = new WorkCommentsTable(activity.getBaseContext());
                                        workCommentsTable.deleteComment(commentID);
                                    }
                                    getComments();
                                }
                            });
                            ad.setNegativeButton(activity.getString(R.string.no), null);
                            ad.setCancelable(true);
                            ad.show();
                        }
                    }
                }
            }
        });
        builder.setCancelable(true);
        if (!items.isEmpty()) {
            builder.show();
        }
    }

    /**
     * Отображение комментариев
     *
     * @param comments - список комментариев
     */
    private void showComments(LinearLayout comments) {
        comments.setVisibility(View.VISIBLE);
    }

    /**
     * Скрытие комментариев
     *
     * @param comments - список комментариев
     */
    private void hideComments(LinearLayout comments) {
        comments.setVisibility(View.GONE);
    }

    /**
     * Метод обновляет список комментариев (используется к примеру после удаления)
     */
    private void getComments() {
        if (work != null) {
            new CommentsList(activity, person, work, workButton, documentButton, personalButton).execute();
        } else {
            new CommentsList(activity, person, document, workID, workButton, documentButton, personalButton).execute();
        }
    }

    /**
     * Запрос на удаление комментария
     */
    class RemoveCommentRequest extends AsyncTask<Void, Void, String> {

        private String commentID;

        public void setCommentID(String commentID) {
            this.commentID = commentID;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result == null) {
                AppMsg.makeText(activity, activity.getString(R.string.error_delete_comment), AppMsg.STYLE_ALERT).show();
                return;
            }
            try {
                ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                // если файл успешно удален - обновляем список
                if (work != null) {
                    // для работ
                    if (errorCode.getResult().equals(Wrapper.NO_ERROR)) {
                        getComments();
                    } else {
                        AppMsg.makeText(activity, errorCode.getMessage(), AppMsg.STYLE_ALERT).show();
                    }
                } else {
                    // для документов
                    if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                        getComments();
                    } else {
                        AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                    }
                }
            } catch (Exception exc) {
                AppMsg.makeText(activity, activity.getString(R.string.error_delete_comment), AppMsg.STYLE_ALERT).show();
            }
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            if (work != null) {
                return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/comments/remove?commentID=" +
                        commentID + "&locale=" + MyApplication.getLang());
            } else {
                return new SendGetRequest(person).requestGET(person.getHost()
                        + "rest/api/docflow/doc/comments/remove?commentID=" + commentID + "&locale=" + MyApplication.getLang());
            }
        }
    }

    public class OnSwipeTouchListener implements View.OnTouchListener {

        private final GestureDetector gestureDetector;
        private View view;

        public OnSwipeTouchListener() {
            gestureDetector = new GestureDetector(activity, new GestureListener());
        }

        public void onSwipeLeft() {
        }

        public void onSwipeRight() {
        }

        public void onFuckingLong(View v) {
        }

        public boolean onTouch(View v, MotionEvent event) {
            view = v;
            return gestureDetector.onTouchEvent(event);
        }

        private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

            private static final int SWIPE_DISTANCE_THRESHOLD = 100;

            private static final int SWIPE_VELOCITY_THRESHOLD = 100;

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                float distanceX = e2.getX() - e1.getX();
                float distanceY = e2.getY() - e1.getY();
                if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) >
                        SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (distanceX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                    return true;
                }
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                onFuckingLong(view);
                super.onLongPress(e);
            }
        }
    }
}