package kz.arta.synergy.workflow.mobile.android.documents.common.activities;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
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 com.pnikosis.materialishprogress.ProgressWheel;
import com.viewpagerindicator.CirclePageIndicator;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.attachments.activities.AttachmentList;
import kz.arta.synergy.workflow.mobile.android.comments.CommentConst;
import kz.arta.synergy.workflow.mobile.android.comments.activities.AddCommentActivity;
import kz.arta.synergy.workflow.mobile.android.comments.activities.CommentsList;
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.AButton;
import kz.arta.synergy.workflow.mobile.android.common.components.CustomImageView;
import kz.arta.synergy.workflow.mobile.android.common.components.OpenFileDialog;
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.offline.get.FormCompletionTable;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorkActionsTable;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorksTable;
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.Const;
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.WrapContentHeightViewPager;
import kz.arta.synergy.workflow.mobile.android.common.utils.Wrapper;
import kz.arta.synergy.workflow.mobile.android.documents.DocumentConst;
import kz.arta.synergy.workflow.mobile.android.documents.common.models.DocumentItem;
import kz.arta.synergy.workflow.mobile.android.documents.offline.DocumentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentAddAttachmentTable;
import kz.arta.synergy.workflow.mobile.android.documents.resolution.activities.ActionResolutionActivity;
import kz.arta.synergy.workflow.mobile.android.documents.route.RoutesConst;
import kz.arta.synergy.workflow.mobile.android.files.FilesConst;
import kz.arta.synergy.workflow.mobile.android.files.activities.FilesTreeActivity;
import kz.arta.synergy.workflow.mobile.android.files.manager.FilesManager;
import kz.arta.synergy.workflow.mobile.android.files.manager.UploadFile;
import kz.arta.synergy.workflow.mobile.android.files.models.Node;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.ResultWorkActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.process.FinishProcessActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.send.SendWorkActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.send.TransmitWorkActivity;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionFormItem;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionResultItem;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkActionsItem;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

/**
 * Created by neox on 05.01.15.
 * Полная информация о документе
 */
public class DocumentInfoActivity extends FragmentActivity {

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

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

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

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

    /**
     * Информация о текущем документе
     */
    private DocumentItem document;

    /**
     * Полная информация о документе
     */
    private RelativeLayout fullDocumentInfo;

    /**
     * Кратка информация о документе
     */
    private RelativeLayout partDocumentInfo;

    /**
     * Имя файла для изображения сделанного с помощью камеры
     */
    private long photoFileName;

    /**
     * Прогресс при открытии файла
     */
    private ProgressDialog addFileProgress;

    /**
     * Форма завершения
     */
    private String formCompletion;

    /**
     * UUID формы завершения
     */
    private String formID;

    /**
     * UUID текущей работы по документу
     */
    private String workID;

    /**
     * Работа по документу
     */
    private WorkItem work;

    /**
     * Тип текущего фильтра
     */
    private String filterType;

    /**
     * UUID текущего документа
     */
    private String documentID;

    /**
     * Текущий фрагмент (информация о работе, имеется только если у документа есть хотя бы одна работа)
     */
    private FragmentDocumentInfoPager currentFragment;

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

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

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

    /**
     * Контейнер для кнопок
     */
    private LinearLayout actionsLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

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

        activity = this;

        // прогресс
        progressBar = (ProgressWheel) findViewById(R.id.document_info_progress_bar);

        // полная плашка
        fullDocumentInfo = (RelativeLayout) findViewById(R.id.full_document_item);

        // неполная плашка
        partDocumentInfo = (RelativeLayout) findViewById(R.id.head_document_info_part);

        // все данные о пользователе
        person = (Person) getIntent().getSerializableExtra(ActivityConst.PERSON);

        // получаем documentID переданный из активити со списком документов
        documentID = getIntent().getStringExtra(ActivityConst.DOCUMENT_ID);

        // тип текущего фильтра (нужен для отображения информации о документе т.к данные немного отличаются)
        filterType = getIntent().getStringExtra(DocumentConst.TYPE_ITEM_DOCUMENTS);

        // если необходимые данные получены - загружаем документ
        if (documentID != null && filterType != null) {
            // получаем информацию о документе
            getDocument(documentID, filterType);
        }

        // основной контейнер для всех компонентов
        mainContent = (SwipeRefreshLayout) findViewById(R.id.document_info_refresh_layout);
        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() {
                        // закрываем полную информацию о документе
                        fullDocumentInfo.setVisibility(View.GONE);
                        // при обновлении экрана - заного грузим все данные
                        getDocument(documentID, filterType);
                    }
                }, 0);
            }
        });

        CustomImageView addButton = (CustomImageView) findViewById(R.id.document_info_add_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showActionsDialog();
            }
        });

        // для информации о документе - по умолчанию идет загрузка комментариев для документа
        CommentsList.commentType = CommentConst.DOCUMENT;
    }

    /**
     * Метод отображает диалог с пунктами добавления чего-либо к документу
     */
    private void showActionsDialog() {
        // fucking hardcode .............
        if (Utils.isOnline(getBaseContext(), person.getHost())) {
            String[] items = {
                    getString(R.string.file_from_storage),
                    getString(R.string.file_from_camera),
                    getString(R.string.photo),
                    getString(R.string.comment)
            };
            AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
            dialog.setTitle(R.string.add);
            dialog.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int pos) {
                    switch (pos) {
                        case 0: {
                            addFileFromStorage();
                            break;
                        }
                        case 1: {
                            addFileFromDevice();
                            break;
                        }
                        case 2: {
                            addFileFromCamera();
                            break;
                        }
                        case 3: {
                            addComment();
                            break;
                        }
                    }
                }
            });
            dialog.setCancelable(true);
            dialog.show();
        } else {
            String[] items = {
                    getString(R.string.file_from_camera),
                    getString(R.string.photo),
                    getString(R.string.comment)
            };
            AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
            dialog.setTitle(R.string.add);
            dialog.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int pos) {
                    switch (pos) {
                        case 0: {
                            addFileFromDevice();
                            break;
                        }
                        case 1: {
                            addFileFromCamera();
                            break;
                        }
                        case 2: {
                            addComment();
                            break;
                        }
                    }
                }
            });
            dialog.setCancelable(true);
            dialog.show();
        }
    }

    /**
     * Метод используется для добавления нового комментария к документу
     */
    private void addComment() {
        Intent intent = new Intent(activity, AddCommentActivity.class);
        intent.putExtra(ActivityConst.WORK_ID, workID);
        intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
        intent.putExtra(ActivityConst.PERSON, person);
        intent.putExtra(ActivityConst.EDIT, false);
        intent.putExtra(ActivityConst.COMMENT_TYPE, CommentsList.commentType);
        if (workID != null) {
            intent.putExtra(ActivityConst.WORK_NAME, work.getName());
        } else {
            intent.putExtra(ActivityConst.WORK_NAME, document.getName());
        }
        startActivityForResult(intent, ActionUtils.COMMENT);
    }

    /**
     * Метод используется для проверки разрешений к Камере
     */
    public boolean isCameraPermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 101);
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * Метод используется для добавления нового файла к документу с камеры
     */
    private void addFileFromCamera() {
        File folder = new File(Environment.getExternalStorageDirectory() +
                File.separator + Const.DIRECTORY_PHOTOS_NAME + File.separator);
        boolean createdDir = true;
        if (!folder.exists()) {
            createdDir = folder.mkdir();
        }
        if (createdDir) {
            photoFileName = System.currentTimeMillis();
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uriSavedImage = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
                    File.separator + Const.DIRECTORY_PHOTOS_NAME + File.separator + photoFileName + Const.DEFAULT_FILE_FORMAT));
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

            //UPD: 2023-11-11 - добавил проверку разрешений, иначе приложение крашится
            if (isCameraPermissionGranted()) {
                startActivityForResult(cameraIntent, ActionUtils.PHOTO);
            }
        }
    }

    /**
     * Метод используется для добавления нового файла к документу с устройства
     */
    private void addFileFromDevice() {
        final OpenFileDialog fileDialog = new OpenFileDialog(activity);
        fileDialog.setOpenDialogListener(new OpenFileDialog.OpenDialogListener() {
            @Override
            public void OnSelectedFile(String fileName) {
                if (Utils.isOnline(activity, person.getHost())) {
                    AddFile addFile = new AddFile();
                    addFile.setFileName(new File(fileName).getName());
                    addFile.setFilePath(fileName);
                    addFile.setDocumentID(document.getDocumentID());
                    addFile.execute();
                } else if (Utils.checkSyncEnables(getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE))) {
                    DocumentAddAttachmentTable add = new DocumentAddAttachmentTable(activity);
                    add.add(document.getDocumentID(), fileName, String.valueOf(System.currentTimeMillis()), document.getName(), new File(fileName).getName());
                    updateAttachmentsList();
                }
            }
        });
        fileDialog.show();
    }

    /**
     * Метод используется для открытия экрана добавления нового файла к документу из хранилища
     */
    private void addFileFromStorage() {
        Intent intent = new Intent(activity, FilesTreeActivity.class);
        intent.putExtra(FilesConst.SHOW_FILES, true);
        intent.putExtra(ActivityConst.PERSON, person);
        startActivityForResult(intent, ActionUtils.UPLOAD_FILE_FROM_STORAGE);
    }

    /**
     * Метод устанавилвает в нужные поля информацию о документе
     */
    private void initHeadComponents(String type) {

        // ------------------------ Компоненты полной плашки ------------------------ //

        // признак происхождения
        ImageView typeIcon = (ImageView) findViewById(R.id.document_icon_document_type_full);

        // резолюция
        ImageView resolutionIcon = (ImageView) findViewById(R.id.document_icon_document_resolution_full);

        // признак контрольности
        ImageView controlledIcon = (ImageView) findViewById(R.id.document_icon_document_controlled_full);

        // бракован ли документ
        ImageView defectiveIcon = (ImageView) findViewById(R.id.document_icon_document_defective_full);

        // отклонен
        ImageView rejectedIcon = (ImageView) findViewById(R.id.document_icon_document_rejected_full);

        // в прогрессе
        ImageView inProgressIcon = (ImageView) findViewById(R.id.document_icon_document_in_progress_full);

        // статус документа
        ImageView statusIcon = (ImageView) findViewById(R.id.status_icon_document_item_full);

        // зарегистрирован ли документ
        ImageView registeredIcon = (ImageView) findViewById(R.id.registration_icon_document_item_full);

        // номер документа
        TextView documentNumber = (TextView) findViewById(R.id.document_number_document_item_full);
        documentNumber.setTypeface(Fonts.getRoman(activity));

        // имя документа
        TextView documentName = (TextView) findViewById(R.id.document_name_full);
        documentName.setTypeface(Fonts.getRoman(activity));

        // отправлено (заголовок)
        TextView createDateTitle = (TextView) findViewById(R.id.full_document_item_create_date_title);
        createDateTitle.setTypeface(Fonts.getRoman(activity));

        // отправлено
        TextView createDate = (TextView) findViewById(R.id.full_document_item_create_date);
        createDate.setTypeface(Fonts.getRoman(activity));

        // от (заголовок)
        TextView fromTitle = (TextView) findViewById(R.id.full_document_item_from_title);
        fromTitle.setTypeface(Fonts.getRoman(activity));

        // от
        TextView from = (TextView) findViewById(R.id.full_document_item_from);
        from.setTypeface(Fonts.getRoman(activity));

        // кому (заголовок)
        TextView toTitle = (TextView) findViewById(R.id.full_document_item_to_title);
        toTitle.setTypeface(Fonts.getRoman(activity));

        // кому
        TextView to = (TextView) findViewById(R.id.full_document_item_to);
        to.setTypeface(Fonts.getRoman(activity));

        RelativeLayout regPanel = (RelativeLayout) findViewById(R.id.document_full_item_registration_panel);

        // регистрация
        TextView registrationTitle = (TextView) findViewById(R.id.full_document_item_registration_title);
        registrationTitle.setTypeface(Fonts.getRoman(activity));

        // зарегистрировал (заголовок)
        TextView regUserTitle = (TextView) findViewById(R.id.full_document_item_registered_user_title);
        regUserTitle.setTypeface(Fonts.getRoman(activity));

        // зарегистрировал
        TextView regUser = (TextView) findViewById(R.id.full_document_item_registered_user);
        regUser.setTypeface(Fonts.getRoman(activity));

        // дата (заголовок)
        TextView regDateTitle = (TextView) findViewById(R.id.full_document_item_registered_date_title);
        regDateTitle.setTypeface(Fonts.getRoman(activity));

        // дата
        TextView regDate = (TextView) findViewById(R.id.full_document_item_registered_date);
        regDate.setTypeface(Fonts.getRoman(activity));

        // отписано (заголовок)
        TextView unsubscribedTitle = (TextView) findViewById(R.id.full_document_item_registered_unsubscribe_title);
        unsubscribedTitle.setTypeface(Fonts.getRoman(activity));

        // отписано
        TextView unsubscribed = (TextView) findViewById(R.id.full_document_item_registered_unsubscribe);
        unsubscribed.setTypeface(Fonts.getRoman(activity));

        // на исполнении (заголовок)
        TextView resUsersTitle = (TextView) findViewById(R.id.full_document_item_registered_res_users_title);
        resUsersTitle.setTypeface(Fonts.getRoman(activity));

        // на исполнении
        TextView resUsers = (TextView) findViewById(R.id.full_document_item_registered_res_users);
        resUsers.setTypeface(Fonts.getRoman(activity));

        // надпись "Скрыть" в полной плашке
        TextView hide = (TextView) findViewById(R.id.head_document_info_hide);
        hide.setTypeface(Fonts.getRoman(activity));
        hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                partDocumentInfo.setVisibility(View.VISIBLE);
                fullDocumentInfo.setVisibility(View.GONE);
            }
        });

        // ------------------------ Компоненты неполной плашки ------------------------ //

        // имя документа в неполной плашке
        TextView documentNamePart = (TextView) findViewById(R.id.head_document_info_name_part);
        documentNamePart.setTypeface(Fonts.getRoman(activity));

        // надпись "Подробнее" в неполной плашке
        TextView showMore = (TextView) findViewById(R.id.head_document_info_more);
        showMore.setTypeface(Fonts.getRoman(activity));
        showMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                partDocumentInfo.setVisibility(View.GONE);
                fullDocumentInfo.setVisibility(View.VISIBLE);
            }
        });

        // тип документа
        if (document.getType().equals(DocumentConst.DOCUMENT)) {
            typeIcon.setImageDrawable(getResources().getDrawable(R.drawable.document_icon));
        } else if (document.getType().equals(DocumentConst.EMAIL)) {
            typeIcon.setImageDrawable(getResources().getDrawable(R.drawable.email_icon));
        }

        // резолюция ли
        if (document.getHasResolution().equals("true")) {
            resolutionIcon.setVisibility(View.VISIBLE);
        } else {
            resolutionIcon.setVisibility(View.GONE);
        }

        // контрольный ли
        if (document.getControlled().equals("true")) {
            controlledIcon.setVisibility(View.VISIBLE);
        } else {
            controlledIcon.setVisibility(View.GONE);
        }

        // бракован ли
        if (document.getDefective().equals("true")) {
            defectiveIcon.setVisibility(View.VISIBLE);
        } else {
            defectiveIcon.setVisibility(View.GONE);
        }

        // отклонен ли
        if (document.getStatusID().equals(DocumentConst.REJECTED)) {
            rejectedIcon.setVisibility(View.VISIBLE);
        } else {
            rejectedIcon.setVisibility(View.GONE);
        }

        // в прогрессе или нет
        if (document.getInProgress().equals("true")) {
            inProgressIcon.setVisibility(View.VISIBLE);
        } else {
            inProgressIcon.setVisibility(View.GONE);
        }

        // если документ зарегистрирован - отображаем его номер
        if (document.getRegistered().equals("true")) {
            if (document.getDocTypeID().equals(DocumentConst.INTERNAL_DOCS)) {
                documentNumber.setText(document.getNumber() + " - " + document.getAuthor());
            } else {
                if (!TextUtils.isEmpty(document.getCorrespondentOrg())) {
                    documentNumber.setText(document.getNumber() + " - " + document.getCorrespondentOrg());
                } else if (!TextUtils.isEmpty(document.getCorrespondent())) {
                    documentNumber.setText(document.getNumber() + " - " + document.getCorrespondent());
                } else {
                    documentNumber.setText(document.getNumber());
                }
            }
            documentNumber.setTypeface(Fonts.getMedium(activity));
            documentNumber.setVisibility(View.VISIBLE);
        } else {
            documentNumber.setVisibility(View.GONE);
        }

        int documentColor;
        if (type.equals(DocumentConst.ALL)) {
            documentColor = activity.getResources().getColor(R.color.default_color_work);
        } else if (document.getStatusID().equals(DocumentConst.REJECTED) && document.getDefective().equals("true")) {
            documentColor = activity.getResources().getColor(R.color.defective_color_document_name);
        } else if (document.getStatusID().equals(DocumentConst.REJECTED)) {
            documentColor = activity.getResources().getColor(R.color.default_color_work);
        } else if (document.getDefective().equals("true")) {
            documentColor = activity.getResources().getColor(R.color.defective_color_document_name);
        } else {
            if (document.getFinished().equals("true") || document.getStatusID().equals(DocumentConst.NOT_STARTED)) {
                documentColor = activity.getResources().getColor(R.color.default_color_work);
            } else {
                if (document.getIsExpired().equals("true")) {
                    documentColor = activity.getResources().getColor(R.color.expired_color_work);
                } else {
                    if (document.getIsSoonExpired().equals("true")) {
                        documentColor = activity.getResources().getColor(R.color.soon_expired_color_work);
                    } else {
                        documentColor = activity.getResources().getColor(R.color.default_color_work);
                    }
                }
            }
        }

        // имя документа
        if (!document.getContent().isEmpty()) {
            Spannable ss1 = new SpannableString(document.getName() + " - " + document.getContent());
            ss1.setSpan(new ForegroundColorSpan(documentColor), 0, document.getName().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            documentName.setText(ss1);
            documentName.setTextColor(activity.getResources().getColor(R.color.document_item_content_color));
            documentNamePart.setText(ss1);
            documentNamePart.setTextColor(activity.getResources().getColor(R.color.document_item_content_color));
        } else {
            documentName.setText(document.getName());
            documentName.setTextColor(documentColor);
            documentNamePart.setText(document.getName());
            documentNamePart.setTextColor(documentColor);
        }

        // дата создания (нужна только для фильтра "Все")
        if (type.equals(DocumentConst.ALL)) {
            if (!TextUtils.isEmpty(document.getFrom()) && !TextUtils.isEmpty(document.getTo())) {
                createDateTitle.setText(getString(R.string.document_info_sent));
            } else {
                if (!TextUtils.isEmpty(document.getFrom())) {
                    createDateTitle.setText(getString(R.string.document_info_get));
                } else if (!TextUtils.isEmpty(document.getTo())) {
                    createDateTitle.setText(getString(R.string.document_info_sent));
                } else {
                    createDateTitle.setText(getString(R.string.document_info_created));
                }
            }
            createDateTitle.setTypeface(Fonts.getRoman(activity));
            createDateTitle.setVisibility(View.VISIBLE);
            createDate.setVisibility(View.VISIBLE);
        } else {
            createDateTitle.setVisibility(View.GONE);
            createDate.setVisibility(View.GONE);
        }

        // дата
        createDate.setTypeface(Fonts.getRoman(activity));
        createDate.setText(DateUtils.getFullDateDocumentItem(document.getCreateDate()));

        // "от"
        if (!TextUtils.isEmpty(document.getFrom())) {
            fromTitle.setTypeface(Fonts.getRoman(activity));
            fromTitle.setVisibility(View.VISIBLE);
            from.setTypeface(Fonts.getRoman(activity));
            from.setVisibility(View.VISIBLE);
            from.setText(document.getFrom());
        } else {
            fromTitle.setVisibility(View.GONE);
            from.setVisibility(View.GONE);
        }

        // "кому"
        if (!TextUtils.isEmpty(document.getTo())) {
            toTitle.setTypeface(Fonts.getRoman(activity));
            toTitle.setVisibility(View.VISIBLE);
            to.setTypeface(Fonts.getRoman(activity));
            to.setVisibility(View.VISIBLE);
            to.setText(document.getTo());
        } else {
            toTitle.setVisibility(View.GONE);
            to.setVisibility(View.GONE);
        }

        if (!type.equals(DocumentConst.ALL)) {
            fromTitle.setVisibility(View.GONE);
            from.setVisibility(View.GONE);
            toTitle.setVisibility(View.GONE);
            to.setVisibility(View.GONE);
            inProgressIcon.setVisibility(View.GONE);
        }

        // если документ зарегистрирован
        if (document.getRegistered().equals("true")) {

            regPanel.setVisibility(View.VISIBLE);
            registrationTitle.setTypeface(Fonts.getRoman(activity));

            if (document.getStatusID().equals(DocumentConst.NOT_STARTED)) {
                registeredIcon.setImageDrawable(getResources().getDrawable(R.drawable.in_registration_icon));
            } else if (document.getRegistered().equals("true")) {
                registeredIcon.setImageDrawable(getResources().getDrawable(R.drawable.registered_icon));
            }
            if (document.getFinished().equals("true")) {
                statusIcon.setImageDrawable(getResources().getDrawable(R.drawable.progress_done_icon));
            } else {
                statusIcon.setImageDrawable(getResources().getDrawable(R.drawable.calendar_status_icon));
            }

            // пользователь зарегистрировавший документ
            if (!TextUtils.isEmpty(document.getRegUser())) {
                regUserTitle.setTypeface(Fonts.getRoman(activity));
                regUserTitle.setVisibility(View.VISIBLE);
                regUser.setTypeface(Fonts.getRoman(activity));
                regUser.setText(document.getRegUser());
                regUser.setVisibility(View.VISIBLE);
            } else {
                regUserTitle.setVisibility(View.GONE);
                regUser.setVisibility(View.GONE);
            }

            // имя пользователя зарегистрировавшего доукмент
            if (!TextUtils.isEmpty(document.getUser())) {
                unsubscribedTitle.setText(person.getSettings().getSignedOff() + ": ");
                unsubscribedTitle.setTypeface(Fonts.getRoman(activity));
                unsubscribedTitle.setVisibility(View.VISIBLE);
                unsubscribed.setTypeface(Fonts.getRoman(activity));
                unsubscribed.setText(document.getUser());
                unsubscribed.setVisibility(View.VISIBLE);
            } else {
                unsubscribedTitle.setVisibility(View.GONE);
                unsubscribed.setVisibility(View.GONE);
            }

            // дата регистрации документа
            if (!TextUtils.isEmpty(document.getRegDate())) {
                regDateTitle.setTypeface(Fonts.getRoman(activity));
                regDateTitle.setVisibility(View.VISIBLE);
                regDate.setTypeface(Fonts.getRoman(activity));
                regDate.setText(DateUtils.getDateDocumentItem(document.getRegDate()));
                regDate.setVisibility(View.VISIBLE);
            } else {
                regDateTitle.setVisibility(View.GONE);
                regDate.setVisibility(View.GONE);
            }

            // исполнители документа
            if (!TextUtils.isEmpty(document.getResUsers())) {
                resUsersTitle.setTypeface(Fonts.getRoman(activity));
                resUsersTitle.setVisibility(View.VISIBLE);
                resUsers.setTypeface(Fonts.getRoman(activity));
                resUsers.setText(document.getResUsers());
                resUsers.setVisibility(View.VISIBLE);
            } else {
                resUsersTitle.setVisibility(View.GONE);
                resUsers.setVisibility(View.GONE);
            }

        } else {
            regPanel.setVisibility(View.GONE);
            registrationTitle.setTypeface(Fonts.getRoman(activity));
        }

        // когда все компоненты проинициализированы - отображаем леяут
        partDocumentInfo.setVisibility(View.VISIBLE);
    }

    /**
     * Инициализация кнопок для работы с комментариями
     */
    private void initCommentsButton() {

        workButton = (Button) findViewById(R.id.comments_work);
        documentButton = (Button) findViewById(R.id.comments_document);
        personalButton = (Button) findViewById(R.id.comments_personal);

        workButton.setTypeface(Fonts.getRoman(activity));
        workButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButton.setBackgroundResource(R.drawable.comments_button_left_selected);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                CommentsList.commentType = CommentConst.WORK;
                updateCommentsList();
            }
        });

        documentButton.setTypeface(Fonts.getRoman(activity));
        documentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center_selected);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                CommentsList.commentType = CommentConst.DOCUMENT;
                updateCommentsList();
            }
        });

        personalButton.setTypeface(Fonts.getRoman(activity));
        personalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right_selected);
                CommentsList.commentType = CommentConst.PERSONAL;
                updateCommentsList();
            }
        });
    }

    /**
     * Метод выполняется после успешной загрузки информации о документе - инициализирует ViewPager
     */
    private void initViewPager(final WorkItem[] works) {
        RelativeLayout viewPagerPanel = (RelativeLayout) findViewById(R.id.document_info_view_pager_panel);
        PagerAdapter workPageAdapter = new PagerAdapter(getSupportFragmentManager(), works);
        WrapContentHeightViewPager workPager = (WrapContentHeightViewPager) viewPagerPanel.findViewById(R.id.document_info_view_pager);
        workPager.setAdapter(workPageAdapter);
        CirclePageIndicator indicator = (CirclePageIndicator) viewPagerPanel.findViewById(R.id.document_info_indicator);
        indicator.setViewPager(workPager);
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {
            }

            @Override
            public void onPageSelected(int position) {
                formID = null;
                workID = document.getActions()[position];
                work = works[position];
                updateCommentsList();
                getFormCompletion(document.getActions()[position]);
                getActions(document.getActions()[position], true);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
        if (works.length == 1) {
            viewPagerPanel.setVisibility(View.VISIBLE);
            indicator.setVisibility(View.GONE);
        } else {
            viewPagerPanel.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Метод вызывается для обновления информации на экране
     */
    public void update() {
        getDocument(documentID, filterType);
    }

    /**
     * Метод загружает информацию о документе
     *
     * @param documentID - documentID
     */
    public void getDocument(final String documentID, final String type) {
        new SendGetRequest("rest/api/docflow/doc/document_info?documentID=" +
                documentID + "&locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                // кнопки связанные с комментариями
                initCommentsButton();
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    result = new DocumentTable(getBaseContext()).getDocument(documentID);
                }
                try {
                    document = RestClient.getGson().fromJson(result, DocumentItem.class);
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                    return;
                }
                if (document != null) {
                    // инициализация информации о документе
                    initHeadComponents(type);
                    // если есть хотя бы одна работа по документу
                    if (document.getActions() != null && document.getActions().length != 0) {
                        // uuid работы
                        workID = document.getActions()[0];
                        // получаем информацию о работе
                        getWorkInfo(document.getActions());
                    } else {
                        workButton.setText(getResources().getString(R.string.document));
                        workButton.setBackgroundResource(R.drawable.comments_button_document_center);
                        workButton.setOnClickListener(null);
                        documentButton.setVisibility(View.GONE);
                        personalButton.setVisibility(View.GONE);
                        getActions(documentID, false);
                    }
                    // комментарии
                    updateCommentsList();
                    // загружаем вложения
                    updateAttachmentsList();
                } else {
                    AppMsg.makeText(activity, getString(R.string.error_parsing), AppMsg.STYLE_ALERT).show();
                }
                mainContent.setRefreshing(false);
                progressBar.setVisibility(View.GONE);
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод получает список подписей для документа
     *
     * @param documentID идентификатор документа
     */
    private void getSignList(String documentID) {
        new SendGetRequest("rest/api/docflow/doc/sign_list?documentID=" + documentID, person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                try {
                    JSONArray jsonArray = new JSONArray(result);
                    boolean addSignButton = true;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        String userID = object.getString("userID");
                        if (userID.equals(person.getUuid())) {
                            addSignButton = false;
                            break;
                        }
                    }
                    if (addSignButton) {
                        if (work != null && (work.getParent_process().equals("agreement-single") ||
                                work.getParent_process().equals("approval-single") ||
                                    work.getParent_process().equals("acquaintance-single"))) {
                            return;
                        }
                        AButton sign = new AButton(activity);
                        sign.setText(R.string.sign);
                        sign.setBackground(AButton.GRAY);
                        sign.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (person.getSettings().isNeedCert() && !person.getSettings().isEnableEDS()) {
                                    AppMsg.makeText(activity, getString(R.string.eds_not_installed), AppMsg.STYLE_ALERT).show();
                                    return;
                                }
                                Intent intent = new Intent(activity, FinishProcessActivity.class);
                                intent.putExtra(ActivityConst.PERSON, person);
                                intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
                                startActivityForResult(intent, ActionUtils.PROCESS_FINISH_INFO);
                            }
                        });
                        actionsLayout.addView(sign);
                    }
                } catch (Exception exc) {
                    // handling error ...
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод загружает информацию о работе по ее workID
     *
     * @param workID - workID
     */
    private void getWorkInfo(final String[] workID) {
        StringBuilder str = new StringBuilder();
        for (String s : workID) {
            str.append("&workID=");
            str.append(s);
        }
        new SendGetRequest("rest/api/workflow/works_by_id?locale=" + MyApplication.getLang() +
                str.toString(), person) {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    WorksTable worksTable = new WorksTable(activity.getBaseContext());
                    List<WorkItem> works = worksTable.getWorksById(workID);
                    result = RestClient.getGson().toJson(works);
                }
                try {
                    // массив с работами
                    WorkItem[] works = RestClient.getGson().fromJson(result, WorkItem[].class);
                    // инициализируем ViewPager после того как работы получены
                    initViewPager(works);
                    // работа
                    work = works[0];
                    // формы завершения
                    getFormCompletion(document.getActions()[0]);
                    // если есть хотя бы одна работа - загружаем кноки
                    getActions(document.getActions()[0], true);
                } catch (JsonSyntaxException exc) {
                    AppMsg.makeText(activity, exc.getLocalizedMessage(), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод для обновления списка вложений
     */
    private void updateAttachmentsList() {
        new AttachmentList(activity, person, document, progressBar).execute();
    }

    /**
     * Метод для обновления списка комментариев
     */
    private void updateCommentsList() {
        new CommentsList(activity, person, document, workID, workButton, documentButton, personalButton).execute();
    }

    /**
     * Метод загружает кнопочки для текущей работы
     *
     * @param uuid - workID
     */
    private void getActions(final String uuid, final boolean isWork) {
        actionsLayout = (LinearLayout) findViewById(R.id.actions);
        actionsLayout.removeAllViews();
        final String url;
        if (isWork) {
            url = "rest/api/workflow/work_actions?workID=" + uuid +
                    "&locale=" + MyApplication.getLang();
        } else {
            url = "rest/api/docflow/document_actions?documentID=" + uuid +
                    "&locale=" + MyApplication.getLang();
        }
        new SendGetRequest(url, person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    if (!isWork) {
                        return;
                    }
                    WorkActionsTable workActionsTable = new WorkActionsTable(activity.getBaseContext());
                    List<WorkActionsItem> workActions = workActionsTable.get(uuid);
                    result = RestClient.getGson().toJson(workActions);
                }
                try {
                    final WorkActionsItem[] actions = RestClient.getGson().fromJson(result, WorkActionsItem[].class);
                    if (actions != null && actions.length != 0) {
                        actionsLayout.setVisibility(View.GONE);
                        actionsLayout.removeAllViewsInLayout();
                        for (int i = 0; i < actions.length; i++) {
                            AButton action = new AButton(activity);
                            action.setText(actions[i].getLabel());
                            action.setId(i);
                            if (actions[i].getColor().equals(ActivityConst.PREFERRED)) {
                                action.setBackground(AButton.GREEN);
                            } else {
                                action.setBackground(AButton.GRAY);
                            }
                            action.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (isWork) {
                                        openActivity(view.getId(), actions);
                                    } else {
                                        openActivity(view.getId(), actions);
                                    }
                                }
                            });
                            actionsLayout.addView(action);
                        }
                        actionsLayout.setVisibility(View.VISIBLE);
                    }
                } catch (JsonSyntaxException exc) {
                    AppMsg.makeText(activity, exc.getLocalizedMessage(), AppMsg.STYLE_ALERT).show();
                }
                mainContent.setRefreshing(false);
                // получение списка подписей документа
                getSignList(document.getDocumentID());
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод отображает панель с типом формы завершения у работы
     */
    private void showPanelFormType(String text, boolean show) {

        Spannable ss = new SpannableString(activity.getString(R.string.form_completion) + ": " + text);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.default_darken_gray)), 0,
                getResources().getString(R.string.form_completion).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        RelativeLayout panel = (RelativeLayout) findViewById(R.id.form_completion_panel);
        if (!show) {
            panel.setVisibility(View.GONE);
            return;
        }

        // имя формы завршения
        TextView name = (TextView) panel.findViewById(R.id.form_completion_name);
        name.setTypeface(Fonts.getMedium(activity));
        name.setText(ss);

        // отображаем
        panel.setVisibility(View.VISIBLE);
    }

    /**
     * Метод отвечает за загрузку и отображение блока "Форма завершения работы"
     */
    private void getFormCompletion(final String workID) {
        new SendGetRequest("rest/api/workflow/work/get_completion_data?workID=" + workID + "&locale=" +
                MyApplication.getLang(), person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    CompletionResultItem form = new FormCompletionTable(activity).getByWorkId(workID);
                    if (form != null && form.getTypeWork() != null && form.getTypeWork().equals("NO_COMPLETION")) {
                        formCompletion = form.getType();
                        showPanelFormType(Utils.getFormCompletion(work.getCompletionFormID(), person, activity, false), true);
                        return;
                    }
                }
                try {
                    CompletionFormItem completionWork = RestClient.getGson().fromJson(result, CompletionFormItem.class);
                    if (completionWork != null && completionWork.getErrorCode() == null) {
                        formCompletion = completionWork.getResult().getType();
                        if (formCompletion.equals(ActivityConst.FORM) && completionWork.getForm_params().length != 0) {
                            formID = completionWork.getForm_params()[2].getFormID();
                        }
                        showPanelFormType(Utils.getFormCompletion(work.getCompletionFormID(), person, activity, false), true);
                    } else {
                        formCompletion = null;
                        showPanelFormType(null, false);
                    }
                } catch (JsonSyntaxException exc) {
                    AppMsg.makeText(activity, exc.getLocalizedMessage(), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_CANCELED) {
            if (requestCode == ActionUtils.COMMENT) {
                updateCommentsList();
            } else if (requestCode == ActionUtils.ATTACHMENT) {
                updateAttachmentsList();
                getActions();
            } else if (requestCode == ActionUtils.PHOTO) {
                resultPhoto();
            } else if (requestCode == ActionUtils.COMPLETION_WORK_COMMENT) {
                update();
            } else if (requestCode == ActionUtils.COMPLETION_WORK_FILE) {
                update();
            } else if (requestCode == ActionUtils.COMPLETION_WORK_FORM) {
                update();
            } else if (requestCode == ActionUtils.SEND_WORK) {
                ActionUtils.updateWorkList(activity);
            } else if (requestCode == ActionUtils.TRANSMIT_WORK) {
                ActionUtils.updateWorkList(activity);
            } else if (requestCode == ActionUtils.REJECT_WORK) {
                update();
            } else if (requestCode == ActionUtils.PROCESS_FINISH_INFO) {
                update();
            } else if (requestCode == ActionUtils.RESOLUTION) {
                update();
            } else if (requestCode == ActionUtils.ACTION_RESOLUTION) {
                ActionUtils.updateWorkList(activity);
            } else if (requestCode == ActionUtils.SAVE_FORM) {
                if (document.getActivate() != null && document.getActivate().equals("true")) {
                    ActionUtils.getRoute(person, activity, document, progressBar, RoutesConst.CHANGE);
                }
            } else if (requestCode == ActionUtils.ROUTE_START) {
                boolean close = data.getBooleanExtra(RoutesConst.CLOSE_DOCUMENT, false);
                if (close) {
                    finish();
                } else {
                    update();
                }
            } else if (requestCode == ActionUtils.UPLOAD_FILE_FROM_STORAGE) {
                Node node = (Node) data.getSerializableExtra(FilesConst.NODE);
                if (node != null) {
                    addFileFromStorage(node.getIdentifier(), UploadFile.INBOX_FILE);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Метод используется для добавления нового файла документ из хранилища
     *
     * @param uuid идентификатор файла
     */
    private void addFileFromStorage(final String uuid, final String container) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    AppMsg.makeText(activity, getString(R.string.error_to_copy_file), AppMsg.STYLE_ALERT).show();
                }
                try {
                    ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                    if (errorCode.getErrorCode().equals(Wrapper.ERROR)) {
                        AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                    } else if (errorCode.getErrorCode().equals(Wrapper.NO_ACCESS)) {
                        addFileFromStorage(uuid, UploadFile.WORK_FILE);
                    }
                } catch (Exception exc) {
                    updateAttachmentsList();
                    getActions();
                }
                super.onPostExecute(result);
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    return new FilesManager(person).copy(documentID, uuid, container);
                } catch (Exception exc) {
                    return null;
                }
            }
        }.execute();
    }

    /**
     * Успешный результат фото
     */
    private void resultPhoto() {
        final String filePath = Environment.getExternalStorageDirectory() + File.separator +
                Const.DIRECTORY_PHOTOS_NAME + File.separator + photoFileName + Const.DEFAULT_FILE_FORMAT;
        final String fileName = Utils.getNewPhotoName(photoFileName, getBaseContext());
        // если есть подключение к интернету - добавляем файл
        if (Utils.isOnline(activity, person.getHost())) {
            AddFile addFile = new AddFile();
            addFile.setFileName(fileName);
            addFile.setFilePath(filePath);
            addFile.setDocumentID(document.getDocumentID());
            addFile.execute();
        } else if (Utils.checkSyncEnables(getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE))) {
            DocumentAddAttachmentTable add = new DocumentAddAttachmentTable(activity);
            add.add(document.getDocumentID(), filePath, String.valueOf(System.currentTimeMillis()), document.getName(), fileName);
            updateAttachmentsList();
        }
    }

    /**
     * Действия с работой
     *
     * @param id - id нажатой кнопки
     */
    private void openActivity(int id, WorkActionsItem[] item) {
        // открываем активити отправки работы
        switch (item[id].getAction()) {
            case ActivityConst.SEND:
                switch (item[id].getOperation()) {
                    case ActivityConst.AGREEMENT:
                        ActionUtils.sendWork(activity, person, work, document, ActionUtils.AGREEMENT,
                                item[id].getAction(), item[id].getOperation());
                        break;
                    case ActivityConst.APPROVAL:
                        ActionUtils.sendWork(activity, person, work, document, ActionUtils.APPROVAL,
                                item[id].getAction(), item[id].getOperation());
                        break;
                    case ActivityConst.ACQUAINTANCE:
                        ActionUtils.sendWork(activity, person, work, document, ActionUtils.ACQUAINTANCE,
                                item[id].getAction(), item[id].getOperation());
                        break;
                }
                break;
            case ActivityConst.TRANSMIT: {
                Intent intent = new Intent(DocumentInfoActivity.this, TransmitWorkActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                intent.putExtra(ActivityConst.WORK_NAME, work.getName());
                startActivityForResult(intent, ActionUtils.TRANSMIT_WORK);
                break;
            }
            case ActivityConst.REASSIGN: {
                Intent intent = new Intent(DocumentInfoActivity.this, SendWorkActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                if (work != null) {
                    intent.putExtra(ActivityConst.FORM_ID, work.getCompletionFormID());
                    intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                } else {
                    intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
                }
                intent.putExtra(ActivityConst.TYPE, ActionUtils.REASSIGN);
                startActivityForResult(intent, ActionUtils.SEND_WORK);
                break;
            }
            case ActivityConst.RESULT: {
                Intent intent = new Intent(DocumentInfoActivity.this, ResultWorkActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.WORK, work);
                startActivityForResult(intent, ActionUtils.REJECT_WORK);
                break;
            }
            case ActivityConst.COMPLETE:
                switch (item[id].getOperation()) {
                    case ActivityConst.POINT_RESULT:
                        // форма завершения файл
                        switch (formCompletion) {
                            case ActivityConst.FILE:
                                ActionUtils.openActivityCompletionWorkFile(activity, person, work);
                                break;
                            case ActivityConst.COMMENT:
                                ActionUtils.openActivityCompletionWorkComment(activity, person, work);
                                break;
                            case ActivityConst.FORM:
                                if (!Utils.isOnline(getBaseContext(), person.getHost())) {
                                    return;
                                }
                                ActionUtils.openActivityCompletionWorkForm(activity, person, work, formID, progressBar);
                                break;
                        }
                        break;
                    case ActivityConst.PROCESS: {
                        if (!person.getSettings().isEnableEDS() && person.getSettings().isNeedCert()) {
                            AppMsg.makeText(activity, getString(R.string.eds_not_installed_on_server), AppMsg.STYLE_ALERT).show();
                        } else {
                            Intent intent = new Intent(DocumentInfoActivity.this, FinishProcessActivity.class);
                            intent.putExtra(ActivityConst.PERSON, person);
                            intent.putExtra(ActivityConst.WORK_NAME, work.getName());
                            intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                            intent.putExtra(ActivityConst.PROC_INST_ID, work.getProcInstID());
                            startActivityForResult(intent, ActionUtils.PROCESS_FINISH_INFO);
                        }
                        break;
                    }
                    case ActivityConst.RESOLUTION_ACTION: {
                        Intent intent = new Intent(this, ActionResolutionActivity.class);
                        intent.putExtra(ActivityConst.PERSON, person);
                        intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                        startActivityForResult(intent, ActionUtils.ACTION_RESOLUTION);
                        break;
                    }
                    case ActivityConst.PROGRESS:
                        currentFragment.finishWorkDialog(activity);
                        break;
                }
                break;
            case ActivityConst.RESOLUTION:
                if (work != null) {
                    ActionUtils.checkSizeResolution(person, work.getActionID(), null, activity, progressBar);
                } else {
                    ActionUtils.checkSizeResolution(person, null, documentID, activity, progressBar);
                }
                break;
            case ActivityConst.REGISTRY:
                ActionUtils.getRoute(person, activity, document, progressBar, RoutesConst.ACTIVATE);
                break;
        }
    }

    public void getActions() {
        if (document.getActions() != null && document.getActions().length != 0) {
            getActions(document.getActions()[0], true);
        } else {
            getActions(documentID, false);
        }
    }

    private class PagerAdapter extends FragmentPagerAdapter {

        WorkItem[] works;

        public PagerAdapter(FragmentManager fm, WorkItem[] works) {
            super(fm);
            this.works = works;
        }

        @Override
        public Fragment getItem(int position) {
            currentFragment = FragmentDocumentInfoPager.newInstance(works[position], person, formCompletion, formID, progressBar);
            return currentFragment;
        }

        @Override
        public int getCount() {
            return works.length;
        }
    }

    /**
     * Класс отвечает за добавление файла к работе
     */
    class AddFile extends AsyncTask<Void, Void, String> {

        String filePath;
        String fileName;
        String documentID;

        public void setDocumentID(String documentID) {
            this.documentID = documentID;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        @Override
        protected void onPreExecute() {
            if (addFileProgress == null) {
                addFileProgress = new ProgressDialog(activity);
                addFileProgress.setMessage(getString(R.string.please_wait));
                addFileProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                addFileProgress.setCancelable(false);
            }
            addFileProgress.show();
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                ErrorCode errorCode;
                try {
                    errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                } catch (JsonSyntaxException exc) {
                    errorCode = null;
                }
                if (errorCode != null) {
                    if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                        updateAttachmentsList();
                        getActions();
                    }
                }
            } else {
                AppMsg.makeText(activity, getString(R.string.error_add_file), AppMsg.STYLE_ALERT).show();
            }
            addFileProgress.dismiss();
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            UploadFile uploadFile = new UploadFile(person, false, UploadFile.INBOX_FILE);
            try {
                return uploadFile.uploadFile(document.getDocumentID(), fileName, filePath, false);
            } catch (Exception exc) {
                return null;
            }
        }
    }
}
