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

import android.app.ActionBar;
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.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
import com.google.gson.JsonSyntaxException;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.ArrayList;
import java.util.Collections;
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.adapters.AdapterAllComments;
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.components.CustomImageView;
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.DateUtils;
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.offline.DocumentCommentsTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentAddCommentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentRemoveCommentTable;

/**
 * Created by neox on 10.04.14.
 * Экран со списком всех комментариев
 */
public class AllCommentsActivity extends Activity {

    private static final int COMMENT = 1;

    /**
     * Прогрессбар
     */
    private ProgressWheel progressBar;

    /**
     * Данные для авторизированного пользователя
     */
    private Person person;

    /**
     * Настройки
     */
    private SharedPreferences settings;

    /**
     * Активити
     */
    private Activity activity;

    /**
     * Главный контейнер (ScrollView with PullToRefresh)
     */
    private SwipeRefreshLayout mainContent;

    /**
     * UUID работы для которой получаются комментарии
     */
    private String workID;

    /**
     * UUID документа для которого получаются комментарии
     */
    private String documentID;

    /**
     * Имя работы для которой получаются комментарии (нужен для оффлайн режима)
     */
    private String name;

    /**
     * Адаптер для списка с комментариями
     */
    private ArrayAdapter adapter;

    /**
     * Список с комментариями
     */
    private List<CommentItem> comments;

    /**
     * UUID выделенного комментария
     */
    private String commentID;

    /**
     * Имя выделнного комментария
     */
    private String commentName;

    /**
     * Тип комментариев (работа/документ/личные)
     */
    private String commentType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_comments_activity);

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
            createEventActionBar();
        }

        activity = this;

        settings = getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        name = intent.getStringExtra(ActivityConst.WORK_NAME);
        commentType = intent.getStringExtra(ActivityConst.COMMENT_TYPE);
        workID = intent.getStringExtra(ActivityConst.WORK_ID);
        documentID = intent.getStringExtra(ActivityConst.DOCUMENT_ID);

        progressBar = (ProgressWheel) findViewById(R.id.all_comments_progress_bar);

        comments = new ArrayList<>();
        adapter = new AdapterAllComments(activity, comments);
        ListView commentsList = (ListView) findViewById(R.id.all_comments_list);
        commentsList.setAdapter(adapter);
        commentsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                commentName = comments.get(i).getComment();
                commentID = comments.get(i).getCommentID();
                showCommentDialog(i);
                return false;
            }
        });

        mainContent = (SwipeRefreshLayout) findViewById(R.id.all_comments_refresh);
        mainContent.setColorSchemeResources(R.color.color1_update_list, R.color.color2_update_list,
                R.color.color3_update_list, R.color.color4_update_list);
        mainContent.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mainContent.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new GetCommentList().execute();
                    }
                }, 0);
            }
        });

        switch (commentType) {
            case CommentConst.DOCUMENT:
                ((TextView) findViewById(R.id.title_action_bar_all_comments)).setText(getString(R.string.document));
                break;
            case CommentConst.WORK:
                ((TextView) findViewById(R.id.title_action_bar_all_comments)).setText(getString(R.string.work));
                break;
            case CommentConst.PERSONAL:
                ((TextView) findViewById(R.id.title_action_bar_all_comments)).setText(getString(R.string.personal));
                break;
        }

        new GetCommentList().execute();
    }

    /**
     * Инициализация кнопок на верхней панели
     */
    private void createEventActionBar() {
        CustomImageView addCommentIcon = (CustomImageView) findViewById(R.id.icon_add_comment_all_comments);
        addCommentIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, AddCommentActivity.class);
                intent.putExtra(ActivityConst.COMMENT_ID, commentID);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.WORK_NAME, name);
                intent.putExtra(ActivityConst.EDIT, false);
                intent.putExtra(ActivityConst.COMMENT_TYPE, commentType);
                if (workID != null) {
                    intent.putExtra(ActivityConst.WORK_ID, workID);
                } else {
                    intent.putExtra(ActivityConst.DOCUMENT_ID, documentID);
                }
                startActivityForResult(intent, COMMENT);
            }
        });
    }

    /**
     * Редактирование комментария
     *
     * @param commentTime время создания
     */
    private void commentIntent(String commentTime) {
        Intent intent = new Intent(activity, AddCommentActivity.class);
        intent.putExtra(ActivityConst.COMMENT_ID, commentID);
        intent.putExtra(ActivityConst.PERSON, person);
        intent.putExtra(ActivityConst.COMMENT_TEXT, commentName);
        intent.putExtra(ActivityConst.COMMENT_TIME, commentTime);
        intent.putExtra(ActivityConst.COMMENT_TYPE, commentType);
        intent.putExtra(ActivityConst.EDIT, true);
        intent.putExtra(ActivityConst.WORK_ID, workID);
        intent.putExtra(ActivityConst.WORK_NAME, name);
        intent.putExtra(ActivityConst.DOCUMENT_ID, documentID);
        startActivityForResult(intent, COMMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_CANCELED && requestCode == COMMENT) {
            progressBar.setVisibility(View.VISIBLE);
            new GetCommentList().execute();
        }
    }

    /**
     * Метод вызывается при долгом нажатии на комментарий
     *
     * @param selectedComment - id выделенного комментария
     */
    private void showCommentDialog(final int selectedComment) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(activity.getString(R.string.edit_comment_title));
        final List<String> items = new ArrayList<>();
        if (comments.get(selectedComment).getIs_editable().equals("true")) {
            items.add(getString(R.string.edit));
        }
        if (comments.get(selectedComment).getIs_deletable().equals("true")) {
            items.add(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(getString(R.string.edit))) {
                    if (Utils.isOnline(activity, person.getHost())) {
                        commentIntent(comments.get(selectedComment).getCreated_label());
                    } else if (Utils.checkSyncEnables(settings) && workID != null) {
                        commentIntent(comments.get(selectedComment).getCreated_label());
                    }
                } else if (items.get(item).equals(getString(R.string.delete))) {
                    if (Utils.isOnline(activity, person.getHost())) {
                        AlertDialog.Builder ad = new AlertDialog.Builder(activity);
                        ad.setTitle(getString(R.string.deleting_comment));
                        ad.setMessage(getString(R.string.are_u_sure_deleting_comment_question) + "?");
                        ad.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                progressBar.setVisibility(View.VISIBLE);
                                RemoveCommentRequest removeCommentRequest = new RemoveCommentRequest();
                                removeCommentRequest.setCommentID(commentID);
                                removeCommentRequest.execute();
                            }
                        });
                        ad.setNegativeButton(getString(R.string.no), null);
                        ad.show();
                    } else if (Utils.checkSyncEnables(settings)) {
                        if (commentID == null) {
                            AlertDialog.Builder ad = new AlertDialog.Builder(activity);
                            ad.setTitle(getString(R.string.deleting_comment));  // заголовок
                            ad.setMessage(getString(R.string.are_u_sure_deleting_comment_question) + "?");
                            ad.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int arg1) {
                                    if (documentID != null && workID == null) {
                                        DocumentAddCommentTable documentAddCommentTable = new DocumentAddCommentTable(activity.getBaseContext());
                                        documentAddCommentTable.removeCommentByData(comments.get(selectedComment).getCreated_label());
                                    } else {
                                        AddComment addComment = new AddComment(activity.getBaseContext());
                                        addComment.removeCommentByData(comments.get(selectedComment).getCreated_label());
                                    }
                                    new GetCommentList().execute();
                                }
                            });
                            ad.setNegativeButton(getString(R.string.no), null);
                            ad.setCancelable(true);
                            ad.show();
                        } else {
                            AlertDialog.Builder ad = new AlertDialog.Builder(activity);
                            ad.setTitle(getString(R.string.deleting_comment));  // заголовок
                            ad.setMessage(getString(R.string.are_u_sure_deleting_comment_question) + "?");
                            ad.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int arg1) {
                                    if (documentID != null && workID == null) {

                                        DocumentRemoveCommentTable documentRemoveCommentTable = new DocumentRemoveCommentTable(activity.getBaseContext());
                                        documentRemoveCommentTable.add(documentID, commentID, "DOCUMENT NAME!", comments.get(selectedComment).getComment());

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

                                    } else {

                                        AddRemoveComment addRemoveComment = new AddRemoveComment(activity.getBaseContext());
                                        addRemoveComment.add(workID, commentID, name, comments.get(selectedComment).getComment());

                                        WorkCommentsTable workCommentsTable = new WorkCommentsTable(activity.getBaseContext());
                                        workCommentsTable.deleteComment(commentID);

                                    }
                                    new GetCommentList().execute();
                                }
                            });
                            ad.setNegativeButton(getString(R.string.no), null);
                            ad.setCancelable(true);
                            ad.show();
                        }
                    }
                }
            }
        });
        builder.setCancelable(true);
        if (items.size() != 0) {
            builder.show();
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

    class GetCommentList extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            comments.clear();
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                CommentItem[] itemComments;
                try {
                    itemComments = RestClient.getGson().fromJson(result, CommentItem[].class);
                } catch (JsonSyntaxException exc) {
                    itemComments = null;
                }
                if (itemComments != null && itemComments.length != 0) {
                    Collections.addAll(comments, itemComments);
                    adapter.notifyDataSetChanged();
                    mainContent.setRefreshing(false);
                }
            } else if (Utils.checkSyncEnables(settings)) {

                List<OfflineComment> addedComments;
                List<CommentItem> commentItemList;

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

                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");
                    comments.add(comment);
                }

                for (CommentItem commentItem : commentItemList) {
                    comments.add(commentItem);
                }

                adapter.notifyDataSetChanged();

            }
            mainContent.setRefreshing(false);
            progressBar.setVisibility(View.GONE);
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            if (workID != null && documentID != null) {
                if (commentType.equals(CommentConst.DOCUMENT)) {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/docflow/doc/comments/list?documentID=" + documentID + "&count=999"
                            + "&locale=" + MyApplication.getLang());
                } else {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/" + workID + "/comments?count=999&type=" + commentType
                            + "&locale=" + MyApplication.getLang());
                }
            } else if (documentID != null) {
                return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/docflow/doc/comments/list?documentID=" + documentID + "&count=999"
                        + "&locale=" + MyApplication.getLang());
            } else if (workID != null) {
                return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/" + workID + "/comments?count=999&type=" + commentType
                        + "&locale=" + MyApplication.getLang());
            } else {
                return null;
            }
        }
    }

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

        String commentID;

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

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                    if (workID != null) {
                        if (errorCode.getResult().equals(Wrapper.NO_ERROR)) {
                            new GetCommentList().execute();
                        } else {
                            AppMsg.makeText(activity, errorCode.getMessage(), AppMsg.STYLE_ALERT).show();
                        }
                    } else {
                        if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                            new GetCommentList().execute();
                        } else {
                            AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                        }
                    }
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_download_comment), AppMsg.STYLE_ALERT).show();
                }
            } else {
                AppMsg.makeText(activity, getString(R.string.error_download_comment), AppMsg.STYLE_ALERT).show();
            }
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            if (workID != 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());
            }
        }
    }
}
