package kz.arta.synergy.workflow.mobile.android.common.offline.add;

import android.content.Context;
import android.util.Base64;

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

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.comments.CommentConst;
import kz.arta.synergy.workflow.mobile.android.comments.manager.AddCommentRequest;
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.offline.ItemResult;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineAttachment;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineChangeProgress;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineComment;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineEditComment;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineRemoveAttachment;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.OfflineRemoveComment;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.completion.OfflineCompletionResult;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.completion.OfflineCompletionWorkComment;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.completion.OfflineCompletionWorkFile;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.LogsTable;
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.Logger;
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.actions.DocumentAddAttachmentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentAddCommentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentEditCommentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentRemoveAttachmentTable;
import kz.arta.synergy.workflow.mobile.android.documents.offline.actions.DocumentRemoveCommentTable;
import kz.arta.synergy.workflow.mobile.android.files.manager.FileUpload;
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.offline.actions.FilesAddFileTable;
import kz.arta.synergy.workflow.mobile.android.files.offline.actions.FilesMoveTable;
import kz.arta.synergy.workflow.mobile.android.files.offline.actions.FilesNewFolderTable;
import kz.arta.synergy.workflow.mobile.android.files.offline.actions.FilesRemoveTable;
import kz.arta.synergy.workflow.mobile.android.files.offline.actions.FilesRenameTable;
import kz.arta.synergy.workflow.mobile.android.works.manager.completion.FinishProcess;
import kz.arta.synergy.workflow.mobile.android.works.manager.completion.RejectWork;
import kz.arta.synergy.workflow.mobile.android.works.models.FinishProcessWorkItem;

/**
 * Created by neox on 11.08.14.
 * Отправка данных из оффлайн режима на сервер
 */
public class AddSync {

    /**
     * Формат даты в жунрале синхронизации
     */
    private SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DEFAULT_DATE_JOURNAL_SYNC);

    private AddComment addComment;
    private AddAttachment addAttachment;
    private AddChangeProgress addChangeProgress;
    private AddRemoveAttachment addRemoveAttachment;
    private AddRemoveComment addRemoveComment;
    private AddEditComment addEditComment;
    private AddCompletionFile addCompletionFile;
    private AddCompletionComment addCompletionComment;
    private AddFinishProcess addFinishProcess;
    private AddResultWork addResultWork;
    private AddFormParams addFormParams;

    private DocumentAddCommentTable documentAddCommentTable;
    private DocumentEditCommentTable documentEditCommentTable;
    private DocumentRemoveCommentTable documentRemoveCommentTable;
    private DocumentRemoveAttachmentTable documentRemoveAttachmentTable;
    private DocumentAddAttachmentTable documentAddAttachmentTable;

    private FilesAddFileTable filesAddFileTable;
    private FilesMoveTable filesMoveTable;
    private FilesNewFolderTable filesNewFolderTable;
    private FilesRemoveTable filesRemoveTable;
    private FilesRenameTable filesRenameTable;

    private Person person;
    private LogsTable logsTable;
    private SendGetRequest sendGetRequest;
    private int errors;
    private double random;

    public AddSync(Context context, Person person) {

        this.person = person;
        sendGetRequest = new SendGetRequest(person);

        addComment = new AddComment(context);
        addAttachment = new AddAttachment(context);
        addChangeProgress = new AddChangeProgress(context);
        addRemoveAttachment = new AddRemoveAttachment(context);
        addRemoveComment = new AddRemoveComment(context);
        addEditComment = new AddEditComment(context);
        addCompletionFile = new AddCompletionFile(context);
        addCompletionComment = new AddCompletionComment(context);
        addFinishProcess = new AddFinishProcess(context);
        addResultWork = new AddResultWork(context);
        addFormParams = new AddFormParams(context);
        logsTable = new LogsTable(context);

        documentAddCommentTable = new DocumentAddCommentTable(context);
        documentEditCommentTable = new DocumentEditCommentTable(context);
        documentRemoveCommentTable = new DocumentRemoveCommentTable(context);
        documentRemoveAttachmentTable = new DocumentRemoveAttachmentTable(context);
        documentAddAttachmentTable = new DocumentAddAttachmentTable(context);

        filesAddFileTable = new FilesAddFileTable(context);
        filesMoveTable = new FilesMoveTable(context);
        filesNewFolderTable = new FilesNewFolderTable(context);
        filesRemoveTable = new FilesRemoveTable(context);
        filesRenameTable = new FilesRenameTable(context);

        random = Math.random() * 1000;
    }

    public void start() {

        logsTable.add(Wrapper.NO_ERROR, "Синхронизация начата",
                sdf.format(System.currentTimeMillis()), random + "");

        addComment();
        editComment();
        addAttachment();
        changeProgress();
        deleteComment();
        deleteAttachment();
        finishedFilesWork();
        finishedCommentsWork();
        finishedProcessInfoWorks();
        finishedResultWorks();

        documentAddComment();
        documentEditComment();
        documentRemoveComment();
        documentRemoveAttachment();
        documentAddAttachment();

        filesAddFile();
        filesMove();
        filesNewFolder();
        filesRemove();
        filesRename();

        if (errors < 1) {
            logsTable.add(Wrapper.NO_ERROR, "Синхронизация завершена успешно",
                    sdf.format(System.currentTimeMillis()), random + "");
        } else {
            logsTable.add(Wrapper.NO_ERROR, "Синхронизация завершена не успешно",
                    sdf.format(System.currentTimeMillis()), random + "");
        }

        errors = 0;
    }

    private void filesAddFile() {
        FilesManager filesManager = new FilesManager(person);
        JSONArray jsonArray = filesAddFileTable.get();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String nodeID = jsonObject.getString("nodeID");
                String fileName = jsonObject.getString("fileName");
                String filePath = jsonObject.getString("filePath");
                String folderName = jsonObject.getString("folderName");
                FileUpload fileUpload = new FileUpload(null, person, fileName, filePath);
                String result = fileUpload.uploadFile();
                if (result != null) {
                    String addFile = filesManager.newFile(nodeID, fileName, result);
                    if (addFile != null) {
                        JSONObject jObject = new JSONObject(addFile);
                        try {
                            jObject.getString("fileID");
                            logsTable.add("1", "Новый файл " + "\"" + fileName + "\"" + " в папку " +
                                    "\"" + folderName + "\"" + " добавлен", sdf.format(System.currentTimeMillis()), random + "");
                        } catch (Exception exc) {
                            String errorMessage = jObject.getString("errorMessage");
                            if (errorMessage.contains("уже существует")) {
                                String file = DateUtils.getDateNewFile(String.valueOf(System.currentTimeMillis())) + "_" + fileName;
                                addFile = filesManager.newFile(nodeID, file, result);
                                jObject = new JSONObject(addFile);
                                try {
                                    jObject.getString("fileID");
                                    logsTable.add("1", "Новый файл " + "\"" + fileName + "\"" + " в папку " +
                                            "\"" + folderName + "\"" + " добавлен", sdf.format(System.currentTimeMillis()), random + "");
                                } catch (Exception e) {
                                    logsTable.add("3", "Новый файл " + "\"" + fileName + "\"" + " в папку " +
                                            "\"" + folderName + "\"" + " не добавлен: " + jObject.getString("errorMessage"), sdf.format(System.currentTimeMillis()), random + "");
                                }
                            } else {
                                logsTable.add("3", "Новый файл " + "\"" + fileName + "\"" + " в папку " +
                                        "\"" + folderName + "\"" + " не добавлен: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                            }
                        }
                    } else {
                        logsTable.add("2", "Новый файл " + "\"" + fileName + "\"" + " в папку " +
                                "\"" + folderName + "\"" + " не добавлен: ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            } catch (Exception exc) {
                Logger.v("exc = " + exc.getLocalizedMessage());
                // handling error
            }
        }
        filesAddFileTable.removeAll();
    }

    private void filesMove() {
        FilesManager filesManager = new FilesManager(person);
        JSONArray jsonArray = filesMoveTable.get();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String oldNode = jsonObject.getString("oldNode");
                String oldNodeName = jsonObject.getString("oldNodeName");
                String newNode = jsonObject.getString("newNode");
                String newNodeName = jsonObject.getString("newNodeName");
                String type = jsonObject.getString("type");
                String result = filesManager.move(oldNode, newNode);
                if (result != null) {
                    JSONObject jObject = new JSONObject(result);
                    String errorCode = jObject.getString("errorCode");
                    if (errorCode != null && errorCode.equals("13")) {
                        String errorMessage = jObject.getString("errorMessage");
                        logsTable.add("3", "Перемещение " + (type.equals("folder") ? "папки" : "файла") + " \"" + oldNodeName + "\"" + ": " +
                                "" + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                    } else {
                        logsTable.add("1", (type.equals("folder") ? "Папка" : "Файл") + " \"" + oldNodeName + "\"" + " перемещен в " +
                                "\"" + newNodeName + "\"", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } else {
                    logsTable.add("2", "Перемещение " + (type.equals("folder") ? "папки" : "файла") + " \"" + oldNodeName + "\"" +
                            ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                }
            } catch (Exception exc) {
                // handling error
            }
        }
        filesMoveTable.removeAll();
    }

    private void filesNewFolder() {
        FilesManager filesManager = new FilesManager(person);
        JSONArray jsonArray = filesNewFolderTable.get();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String nodeID = jsonObject.getString("nodeID");
                String folderName = jsonObject.getString("folderName");
                String newFolderName = jsonObject.getString("newFolderName");
                String result = filesManager.newFolder(nodeID, folderName);
                if (result != null) {
                    JSONObject jObject = new JSONObject(result);
                    try {
                        jObject.getString("folderID");
                        logsTable.add("1", "Новая папка " + "\"" + folderName + "\"" + " в папку " +
                                "\"" + newFolderName + "\"" + " добавлена", sdf.format(System.currentTimeMillis()), random + "");
                    } catch (Exception exc) {
                        String errorMessage = jObject.getString("errorMessage");
                        if (errorMessage.contains("уже существует")) {
                            String folder = folderName + "_" + DateUtils.getDateNewFile(String.valueOf(System.currentTimeMillis()));
                            result = filesManager.newFolder(nodeID, folder);
                            if (result != null) {
                                jsonObject = new JSONObject(result);
                                try {
                                    jsonObject.getString("folderID");
                                    logsTable.add("1", "Новая папка " + "\"" + folder + "\"" + " в папку " +
                                            "\"" + newFolderName + "\"" + " добавлена", sdf.format(System.currentTimeMillis()), random + "");
                                } catch (Exception e) {
                                    logsTable.add("3", "Новая папка " + "\"" + folder + "\"" + " в папку " +
                                            "" + "\"" + newFolderName + "\"" + " не добавлена: " + jsonObject.getString("errorMessage"), sdf.format(System.currentTimeMillis()), random + "");
                                }
                            }
                        } else {
                            logsTable.add("3", "Новая папка " + "\"" + folderName + "\"" + " в папку " +
                                    "" + "\"" + newFolderName + "\"" + " не добавлена: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                        }
                    }
                } else {
                    logsTable.add("2", "Новая папка " + "\"" + folderName + "\"" + " в папку " +
                            "\"" + newFolderName + "\"" + " не добавлена: ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                }
            } catch (Exception exc) {
                // handling error
                Logger.v("exc = " + exc.getLocalizedMessage());
            }
        }
        filesNewFolderTable.removeAll();
    }

    private void filesRemove() {
        FilesManager filesManager = new FilesManager(person);
        JSONArray jsonArray = filesRemoveTable.get();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String nodeID = jsonObject.getString("nodeID");
                String nodeName = jsonObject.getString("nodeName");
                String result = filesManager.remove(nodeID);
                String type = jsonObject.getString("type");
                if (result != null) {
                    JSONObject jObject = new JSONObject(result);
                    String errorCode = jObject.getString("errorCode");
                    if (errorCode != null && errorCode.equals("13")) {
                        String errorMessage = jObject.getString("errorMessage");
                        logsTable.add("3", "Удаление " + (type.equals("folder") ? "папки" : "файла") + " \"" + nodeName + "\"" + " " +
                                "не синхронизировано: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                    } else {
                        logsTable.add("1", "Удаление " + (type.equals("folder") ? "папки" : "файла") + " \"" + nodeName + "\"" +
                                " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } else {
                    logsTable.add("2", "Удаление " + (type.equals("folder") ? "папки" : "файла") + " \"" + nodeName + "\"" +
                            " : ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                }
            } catch (Exception exc) {
                // handling error
            }
        }
        filesRemoveTable.removeAll();
    }

    private void filesRename() {
        FilesManager filesManager = new FilesManager(person);
        JSONArray jsonArray = filesRenameTable.get();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String nodeID = jsonObject.getString("nodeID");
                String newName = jsonObject.getString("newName");
                String result = filesManager.rename(nodeID, newName);
                String type = jsonObject.getString("type");
                if (result != null) {
                    JSONObject jObject = new JSONObject(result);
                    String errorCode = jObject.getString("errorCode");
                    if (errorCode != null && errorCode.equals("13")) {
                        String errorMessage = jObject.getString("errorMessage");
                        logsTable.add("3", "Переименование " + (type.equals("folder") ? "папки" : "файла") + " \"" + newName + "\"" +
                                " не синхронизировано: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                    } else {
                        logsTable.add("1", "Переименование " + (type.equals("folder") ? "папки" : "файла") + " синхронизировано, новое значение: " +
                                "" + "\"" + newName + "\"", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } else {
                    logsTable.add("2", "Переименование " + (type.equals("folder") ? "папки" : "файла") + " \"" + newName + "\"" +
                            " : ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                }
            } catch (Exception exc) {
                // handling error
            }
        }
        filesRenameTable.removeAll();
    }

    private void documentAddAttachment() {
        List<OfflineAttachment> offlineAttachments = documentAddAttachmentTable.get();
        for (OfflineAttachment offlineAttachment : offlineAttachments) {
            if (errors < 6) {
                try {
                    UploadFile uploadFile = new UploadFile(person, false, UploadFile.INBOX_FILE);
                    String result = uploadFile.uploadFile(offlineAttachment.getActionID(), offlineAttachment.getFilename(), offlineAttachment.getFilepath(), false);
                    if (result != null) {
                        JSONObject jsonObject = new JSONObject(result);
                        String errorCode = jsonObject.getString("errorCode");
                        String errorMessage = jsonObject.getString("errorMessage");
                        if (errorCode != null && (errorCode.equals("13") || errorCode.equals("666"))) {
                            logsTable.add("3", "Новый файл " + "\"" + offlineAttachment.getFilename() + "\"" + " к документу " + "\"" +
                                            offlineAttachment.getName() + "\"" + " добавлен в папку \"Прочие\": " + "Отсутствует доступ к папке \"Приложения\"",
                                    sdf.format(System.currentTimeMillis()), random + "");
                            if (errorMessage.startsWith("This node already exists")) {
                                String format = Utils.getFormatByFilename(offlineAttachment.getFilename());
                                uploadFile = new UploadFile(person, false, UploadFile.WORK_FILE);
                                uploadFile.uploadFile(offlineAttachment.getActionID(), offlineAttachment.getFilename().replace(format, "") + "_" +
                                        DateUtils.getDateFromMilliseconds(String.valueOf(System.currentTimeMillis())) + format, offlineAttachment.getFilepath(), false);
                            }
                        } else {
                            logsTable.add("1", "Новый файл " + "\"" + offlineAttachment.getFilename() + "\"" + " к документу " + "\"" +
                                    offlineAttachment.getName() + "\"" + " добавлен", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Новый файл " + "\"" + new File(offlineAttachment.getFilepath()).getName() + "\"" + " к документу " + "\"" +
                                offlineAttachment.getName() + "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } catch (Exception exc) {
                    // handling error ...
                }
            }
        }
        documentAddAttachmentTable.removeAll();
    }

    private void documentRemoveAttachment() {
        List<OfflineRemoveAttachment> offlineRemoveAttachments = documentRemoveAttachmentTable.get();
        for (OfflineRemoveAttachment offlineRemoveAttachment : offlineRemoveAttachments) {
            if (errors < 6) {
                try {
                    String result = sendGetRequest.requestGET(person.getHost() + "rest/api/docflow/doc/attachment/remove?fileUUID="
                            + offlineRemoveAttachment.getNodeUUID() + "&locale=" + MyApplication.getLang());
                    if (result != null) {
                        JSONObject jsonObject = new JSONObject(result);
                        String errorCode = jsonObject.getString("errorCode");
                        String errorMessage = jsonObject.getString("errorMessage");
                        if (errorCode != null && errorCode.equals("13")) {
                            logsTable.add("3", "Удаление файла " + "\"" + offlineRemoveAttachment.getFileName() + "\"" + " документа " + "\"" +
                                    offlineRemoveAttachment.getName() + "\"" + " не синхронизировано: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                        } else {
                            logsTable.add("1", "Удаление файла " + "\"" + offlineRemoveAttachment.getFileName() + "\"" + " документа " + "\"" +
                                    offlineRemoveAttachment.getName() + "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Удаление файла " + "\"" + offlineRemoveAttachment.getNodeUUID() + "\"" + " документа " + "\"" +
                                offlineRemoveAttachment.getName() + "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } catch (Exception exc) {
                    // handling error ...
                }
            }
        }
        documentRemoveAttachmentTable.removeAll();
    }

    private void documentAddComment() {
        List<OfflineComment> commentList = documentAddCommentTable.get();
        for (OfflineComment comment : commentList) {
            if (errors < 6) {
                try {
                    AddCommentRequest addComment = new AddCommentRequest();
                    addComment.setPerson(person);
                    addComment.setEdit(false);
                    addComment.setDocumentID(comment.getActionID());
                    addComment.setCommentText(comment.getComment());
                    addComment.setCommentType(CommentConst.DOCUMENT);
                    String result = addComment.addComment();
                    if (result != null) {
                        JSONObject jsonObject = new JSONObject(result);
                        String errorCode = jsonObject.getString("errorCode");
                        if (errorCode.equals("0")) {
                            logsTable.add("1", "Новый комментарий " + "\"" + comment.getComment() + "\"" + " к документу " + "\""
                                    + comment.getName() + "\"" + " добавлен", sdf.format(System.currentTimeMillis()), random + "");
                        } else {
                            logsTable.add("3", "Новый комментарий " + "\"" + comment.getComment() + "\"" + " к документу " + "\""
                                    + comment.getName() + "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Новый комментарий " + "\"" + comment.getComment() + "\"" + " к документу " + "\"" +
                                comment.getName() + "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } catch (Exception exc) {
                    // handling error ...
                }
            }
        }
        documentAddCommentTable.removeAll();
    }

    private void documentEditComment() {
        List<OfflineEditComment> commentList = documentEditCommentTable.get();
        for (OfflineEditComment comment : commentList) {
            if (errors < 6) {
                try {
                    AddCommentRequest addComment = new AddCommentRequest();
                    addComment.setPerson(person);
                    addComment.setEdit(false);
                    addComment.setDocumentID(comment.getActionID());
                    addComment.setCommentText(comment.getComment());
                    addComment.setCommentType(CommentConst.DOCUMENT);
                    addComment.setCommentID(comment.getCommentID());
                    addComment.setEdit(true);
                    String result = addComment.addComment();
                    if (result != null) {
                        JSONObject jsonObject = new JSONObject(result);
                        String errorCode = jsonObject.getString("errorCode");
                        if (errorCode.equals("0")) {
                            logsTable.add("1", "Изменение комментария к документу " + "\"" + comment.getName() + "\"" +
                                    " синхронизировано, новое значение: " + "\"" + comment.getComment() + "\"", sdf.format(System.currentTimeMillis()), random + "");
                        } else {
                            String errorMessage = jsonObject.getString("errorMessage");
                            logsTable.add("3", "Изменение комментария к документу " + "\"" + comment.getComment() + "\""
                                    + comment.getName() + "\"" + " не синхронизировано: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Изменение комментария к документу " + "\"" + comment.getComment() + "\""
                                + comment.getName() + "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } catch (Exception exc) {
                    // handling error ...
                }
            }
        }
        documentEditCommentTable.removeAll();
    }

    private void documentRemoveComment() {
        List<OfflineRemoveComment> commentList = documentRemoveCommentTable.get();
        for (OfflineRemoveComment comment : commentList) {
            if (errors < 6) {
                try {
                    String result = sendGetRequest.requestGET(person.getHost() + "rest/api/docflow/doc/comments/remove?commentID=" + comment.getCommentID());
                    if (result != null) {
                        JSONObject jsonObject = new JSONObject(result);
                        String errorCode = jsonObject.getString("errorCode");
                        String errorMessage = jsonObject.getString("errorMessage");
                        if (errorCode != null && errorCode.equals("13")) {
                            logsTable.add("3", "Удаление комментария " + "\"" + comment.getCommentName() + "\"" + " к документу " + "\""
                                    + comment.getName() + "\"" + " не синхронизировано: " + errorMessage, sdf.format(System.currentTimeMillis()), random + "");
                        } else {
                            logsTable.add("1", "Удаление комментария " + "\"" + comment.getCommentName() + "\"" + " к документу "
                                    + "\"" + comment.getName() + "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    } else {
                        logsTable.add("2", "Удаление комментария " + "\"" + comment.getCommentName() + "\"" + " к документу " + "\""
                                + comment.getName() + "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                } catch (Exception exc) {
                    // handling error...
                }
            }
        }
        documentRemoveCommentTable.removeAll();
    }

    /**
     * Чистка таблиц после синхронизации
     */
    public void clear() {
        addComment.remove();
        addChangeProgress.remove();
        addRemoveAttachment.remove();
        addRemoveComment.remove();
        addEditComment.remove();
        addCompletionFile.remove();
        addCompletionComment.remove();
        addFinishProcess.remove();
        addResultWork.remove();
        addFormParams.remove();
    }

    /**
     * Завершение работ с формой завершения "результат"
     */
    private void finishedResultWorks() {
        List<OfflineCompletionResult> offlineCompletionResult = addResultWork.get();
        if (offlineCompletionResult != null) {
            for (OfflineCompletionResult anOfflineCompletionResult : offlineCompletionResult) {
                if (anOfflineCompletionResult.getSignal().equals("accept")) {
                    if (errors < 6) {
                        String accept = sendGetRequest.requestGET(person.getHost() +
                                "rest/api/workflow/work/accept_result?workID=" + anOfflineCompletionResult.getActionID()
                                + "&resultID=" + anOfflineCompletionResult.getResultID() + "&locale=" + MyApplication.getLang());
                        if (accept != null) {
                            ErrorCode errorCode = RestClient.getGson().fromJson(accept, ErrorCode.class);
                            if (errorCode != null) {
                                if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                    logsTable.add("1", "Завершение работы " + "\"" + anOfflineCompletionResult.getName() +
                                            "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                                } else {
                                    logsTable.add("3", "Завершение работы " + "\"" + anOfflineCompletionResult.getName() +
                                            "\"" + " не синхронизировано: " + errorCode.getErrorMessage(), sdf.format(System.currentTimeMillis()), random + "");
                                }
                            }
                        } else {
                            errors++;
                            logsTable.add("2", "Завершение работы " + "\"" + anOfflineCompletionResult.getName() +
                                    "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    }
                } else if (anOfflineCompletionResult.getSignal().equals("reject")) {
                    if (errors < 6) {
                        RejectWork rejectWorkRequest = new RejectWork();
                        rejectWorkRequest.setStartDate(anOfflineCompletionResult.getStartDate());
                        rejectWorkRequest.setFinishDate(anOfflineCompletionResult.getFinishDate());
                        rejectWorkRequest.setComment(anOfflineCompletionResult.getComment());
                        rejectWorkRequest.setProgress(anOfflineCompletionResult.getProgress());
                        rejectWorkRequest.setResultID(anOfflineCompletionResult.getResultID());
                        rejectWorkRequest.setWorkID(anOfflineCompletionResult.getActionID());
                        rejectWorkRequest.setPerson(person);
                        String reject = rejectWorkRequest.reject();
                        if (reject != null) {
                            ErrorCode errorCode = RestClient.getGson().fromJson(reject, ErrorCode.class);
                            if (errorCode != null) {
                                if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                    logsTable.add("1", "Завершение работы " + "\"" + anOfflineCompletionResult.getName() +
                                            "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                                } else {
                                    logsTable.add("3", "Завершение работы " + "\"" + anOfflineCompletionResult.getName() +
                                            "\"" + " не синхронизировано: " + errorCode.getErrorMessage(), sdf.format(System.currentTimeMillis()), random + "");
                                }
                            }
                        } else {
                            errors++;
                            logsTable.add("2", "Завершение работы " + "\"" + anOfflineCompletionResult.getName() +
                                    "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    }
                }
            }
        }
    }

    /**
     * Удаление вложений из работ
     */
    private void deleteAttachment() {
        List<OfflineRemoveAttachment> offlineRemoveAttachments = addRemoveAttachment.get();
        if (offlineRemoveAttachments != null) {
            for (OfflineRemoveAttachment offlineRemoveAttachment : offlineRemoveAttachments) {
                if (errors < 6) {
                    String result = sendGetRequest.requestGET(person.getHost() + "rest/api/workflow/work/remove_file?nodeUUID="
                            + offlineRemoveAttachment.getNodeUUID() + "&locale=" + MyApplication.getLang());
                    if (result != null) {
                        ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                        if (errorCode != null) {
                            if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                logsTable.add("1", "Удаление файла " + "\"" +
                                                offlineRemoveAttachment.getFileName() + "\"" + " работы " + "\"" +
                                                offlineRemoveAttachment.getName() + "\"" + " синхронизировано",
                                        sdf.format(System.currentTimeMillis()), random + "");
                            } else {
                                logsTable.add("3", "Удаление файла " + "\"" +
                                                offlineRemoveAttachment.getFileName() + "\"" + " работы " + "\"" +
                                                offlineRemoveAttachment.getName() + "\"" + " не синхронизировано: " + errorCode.getErrorMessage(),
                                        sdf.format(System.currentTimeMillis()), random + "");
                            }
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Удаление файла " + "\"" +
                                        offlineRemoveAttachment.getNodeUUID() + "\"" + " работы " + "\"" +
                                        offlineRemoveAttachment.getName() + "\"" + ": ошибка синхронизации",
                                sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Удаление комментариев
     */
    private void deleteComment() {
        List<OfflineRemoveComment> offlineRemoveComments = addRemoveComment.get();
        if (offlineRemoveComments != null) {
            for (OfflineRemoveComment offlineRemoveComment : offlineRemoveComments) {
                if (errors < 6) {
                    String result = sendGetRequest.requestGET(person.getHost() + "rest/api/workflow/work/comments/remove?commentID="
                            + offlineRemoveComment.getCommentID() + "&locale=" + MyApplication.getLang());
                    if (result != null) {
                        ItemResult itemResult = RestClient.getGson().fromJson(result, ItemResult.class);
                        if (itemResult != null) {
                            if (itemResult.getResult().equals(Wrapper.NO_ERROR)) {
                                logsTable.add("1", "Удаление комментария " + "\"" +
                                        offlineRemoveComment.getCommentName() + "\"" + " к работе " + "\"" + offlineRemoveComment.getName()
                                        + "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                            } else {
                                logsTable.add("3", "Удаление комментария " + "\"" +
                                                offlineRemoveComment.getCommentName() + "\"" + " к работе " + "\"" + offlineRemoveComment.getName()
                                                + "\"" + " не синхронизировано: " + itemResult.getMessage(),
                                        sdf.format(System.currentTimeMillis()), random + "");
                            }
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Удаление комментария " + "\"" +
                                offlineRemoveComment.getCommentName() + "\"" + " к работе " + "\"" + offlineRemoveComment.getName() +
                                "\"" + ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Изменение прогресса работ
     */
    private void changeProgress() {
        List<OfflineChangeProgress> offlineChangeProgress = addChangeProgress.get();
        if (offlineChangeProgress != null) {
            for (OfflineChangeProgress offlineChangeProgres : offlineChangeProgress) {
                if (errors < 6) {
                    String result = sendGetRequest.requestGET(person.getHost() + "rest/api/workflow/work/set_progress?workID=" +
                            offlineChangeProgres.getActionID() + "&progress=" + offlineChangeProgres.getProgress()
                            + "&locale=" + MyApplication.getLang());
                    if (result != null) {
                        ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                        if (errorCode != null) {
                            if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                if (offlineChangeProgres.getProgress().equals("100")) {
                                    logsTable.add("1", "Завершение работы " + "\"" + offlineChangeProgres.getName()
                                            + "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                                } else {
                                    logsTable.add("1", "Изменение прогресса работы " + "\"" +
                                            offlineChangeProgres.getName() + "\"" + " синхронизировано, новое значение - " +
                                            offlineChangeProgres.getProgress() + "%", sdf.format(System.currentTimeMillis()), random + "");
                                }
                            } else {
                                if (offlineChangeProgres.getProgress().equals("100")) {
                                    logsTable.add("3", "Завершение работы " + "\"" +
                                                    offlineChangeProgres.getName() + "\"" + " не синхронизировано: " + errorCode.getErrorMessage(),
                                            sdf.format(System.currentTimeMillis()), random + "");
                                } else {
                                    logsTable.add("3", "Изменение прогресса работы " + "\"" +
                                                    offlineChangeProgres.getName() + "\"" + " не синхронизировано: " + errorCode.getErrorMessage(),
                                            sdf.format(System.currentTimeMillis()), random + "");
                                }
                            }
                        }
                    } else {
                        errors++;
                        if (offlineChangeProgres.getProgress().equals("100")) {
                            logsTable.add("2", "Завершение работы " + "\"" +
                                            offlineChangeProgres.getName() + "\"" + ": ошибка синхронизации",
                                    sdf.format(System.currentTimeMillis()), random + "");
                        } else {
                            logsTable.add("2", "Изменение прогресса работы " + "\"" +
                                            offlineChangeProgres.getName() + "\"" + ": ошибка синхронизации",
                                    sdf.format(System.currentTimeMillis()), random + "");
                        }
                    }
                }
            }
        }
    }

    /**
     * Добавление вложений к работам
     */
    private void addAttachment() {
        List<OfflineAttachment> offlineAttachments = addAttachment.get();
        if (offlineAttachments != null) {
            for (OfflineAttachment offlineAttachment : offlineAttachments) {
                if (errors < 6) {
                    UploadFile uploadFile = new UploadFile(person, false, UploadFile.INBOX_FILE);
                    String result = uploadFile.uploadFile(offlineAttachment.getActionID(),
                            offlineAttachment.getFilename(),
                                offlineAttachment.getFilepath(), true);
                    if (result != null) {
                        ItemResult itemResult = RestClient.getGson().fromJson(result, ItemResult.class);
                        if (itemResult != null) {
                            if (itemResult.getResult().equals(Wrapper.NO_ERROR)) {
                                addAttachment.removeAttachmentByDate(offlineAttachment.getDate());
                                logsTable.add("1", "Новый файл " + "\"" + offlineAttachment.getFilename() + "\"" +
                                                " к работе " + "\"" + offlineAttachment.getName() + "\"" + " добавлен",
                                        sdf.format(System.currentTimeMillis()), random + "");
                            } else {
                                if (itemResult.getMessage().startsWith("This node already exists")) {
                                    String format = Utils.getFormatByFilename(offlineAttachment.getFilename());
                                    uploadFile = new UploadFile(person, false, UploadFile.INBOX_FILE);
                                    uploadFile.uploadFile(offlineAttachment.getActionID(),
                                            offlineAttachment.getFilename().replace(format, "") + "_" +
                                                    DateUtils.getDateFromMilliseconds(String.valueOf(System.currentTimeMillis())) + format, offlineAttachment.getFilepath(), true);
                                }
                            }
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Новый файл " + "\"" + new File(offlineAttachment.getFilepath()).getName() + "\"" +
                                        " к работе " + "\"" + offlineAttachment.getName() + "\"" + ": ошибка синхронизации",
                                sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Добавление комментариев к работам
     */
    private void addComment() {
        List<OfflineComment> offlineComments = addComment.get();
        if (offlineComments != null) {
            for (OfflineComment offlineComment : offlineComments) {
                if (errors < 6) {
                    AddCommentRequest addComment = new AddCommentRequest();
                    addComment.setPerson(person);
                    addComment.setEdit(false);
                    addComment.setWorkID(offlineComment.getActionID());
                    addComment.setCommentText(offlineComment.getComment());
                    addComment.setCommentType(offlineComment.getType());
                    String result = addComment.addComment();
                    if (result != null) {
                        ItemResult itemResult = RestClient.getGson().fromJson(result, ItemResult.class);
                        if (itemResult != null) {
                            if (itemResult.getResult().equals(Wrapper.NO_ERROR)) {
                                logsTable.add("1", "Новый комментарий " + "\"" + offlineComment.getComment() + "\"" +
                                                " к работе " + "\"" + offlineComment.getName() + "\"" + " добавлен",
                                        sdf.format(System.currentTimeMillis()), random + "");
                            } else {
                                logsTable.add("3", "Новый комментарий " + "\"" + offlineComment.getComment() + "\"" +
                                                " к работе " + "\"" + offlineComment.getName() + "\"" + " не добавлен: " + itemResult.getMessage(),
                                        sdf.format(System.currentTimeMillis()), random + "");
                            }
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Новый комментарий " + "\"" + offlineComment.getComment() + "\"" +
                                        " к работе " + "\"" + offlineComment.getName() + "\"" + ": ошибка синхронизации",
                                sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Редактирование комментариев
     */
    private void editComment() {
        List<OfflineEditComment> editComments = addEditComment.get();
        if (editComments != null) {
            for (OfflineEditComment editComment : editComments) {
                if (errors < 6) {
                    AddCommentRequest addComment = new AddCommentRequest();
                    addComment.setPerson(person);
                    addComment.setEdit(true);
                    addComment.setWorkID(editComment.getActionID());
                    addComment.setCommentText(editComment.getComment());
                    addComment.setCommentID(editComment.getCommentID());
                    addComment.setCommentType(CommentConst.WORK);
                    String result = addComment.addComment();
                    if (result != null) {
                        ItemResult itemResult = RestClient.getGson().fromJson(result, ItemResult.class);
                        if (itemResult != null) {
                            if (itemResult.getResult().equals(Wrapper.NO_ERROR)) {
                                logsTable.add("1", "Изменение комментария к работе " + "\"" + editComment.getName() + "\"" +
                                                " синхронизировано, новое значение: " + "\"" + editComment.getComment() + "\"",
                                        sdf.format(System.currentTimeMillis()), random + "");
                            } else {
                                logsTable.add("3", "Изменение комментария " + "\"" + editComment.getComment() + "\"" +
                                                " к работе " + "\"" + editComment.getName() + "\"" + " не синхронизировано: " + itemResult.getMessage(),
                                        sdf.format(System.currentTimeMillis()), random + "");
                            }
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Изменение комментария " + "\"" + editComment.getComment() + "\"" +
                                        " к работе " + "\"" + editComment.getName() + "\"" + ": ошибка синхронизации",
                                sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Завершение работ с формой завершения файл
     */
    private void finishedFilesWork() {
        List<OfflineCompletionWorkFile> works = addCompletionFile.get();
        if (works != null) {
            for (OfflineCompletionWorkFile work : works) {
                if (errors < 6) {
                    if (work.getFromDevice().equals("true")) {
                        UploadFile uploadFile = new UploadFile(person, true, UploadFile.INBOX_FILE);
                        String tmpFilePath = uploadFile.uploadFile(work.getWorkID(),
                                work.getFile_name(), work.getFile_path(), true);
                        if (tmpFilePath != null) {
                            String result = finishWork(work.getWorkID(), work.getFile_name(), null, "FILE", null, tmpFilePath, "file");
                            if (result != null) {
                                ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                                if (errorCode != null) {
                                    if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                        logsTable.add("1", "Завершение работы " + "\"" + work.getName() + "\"" +
                                                " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                                    } else {
                                        logsTable.add("3", "Завершение работы " + "\"" + work.getName() + "\"" +
                                                        " не синхронизировано : " + errorCode.getErrorMessage() + " (в \"Прочие\" добавлен файл формы завершения)",
                                                sdf.format(System.currentTimeMillis()), random + "");
                                        try {
                                            uploadFile = new UploadFile(person, false, UploadFile.WORK_FILE);
                                            result = uploadFile.uploadFile(work.getWorkID(), work.getFile_name(), work.getFile_path(), true);
                                            ItemResult itemResult = RestClient.getGson().fromJson(result, ItemResult.class);
                                            if (itemResult != null) {
                                                if (itemResult.getResult().equals("13")) {
                                                    String format = Utils.getFormatByFilename(work.getFile_name());
                                                    uploadFile = new UploadFile(person, false, UploadFile.WORK_FILE);
                                                    uploadFile.uploadFile(work.getWorkID(),
                                                            work.getFile_name().replace(format, "") + "_" +
                                                                    DateUtils.getDateFromMilliseconds(String.valueOf(System.currentTimeMillis())) +
                                                                    format, work.getFile_path(), true);
                                                }
                                            }
                                        } catch (Exception exc) {
                                            Logger.v(exc.getLocalizedMessage());
                                        }
                                    }
                                }
                            } else {
                                errors++;
                                logsTable.add("2", "Завершение работы " + "\"" + work.getName() + "\"" +
                                        ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                            }
                        }
                    } else {
                        String result = finishWork(work.getWorkID(), work.getFile_name(),
                                work.getFile_identifier(), "FILE", null, null, "work");
                        if (result != null) {
                            ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                            if (errorCode != null) {
                                if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                    logsTable.add("1", "Завершение работы " + "\"" + work.getName() + "\"" +
                                            " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                                } else {
                                    logsTable.add("3", "Завершение работы " + "\"" + work.getName() + "\"" +
                                                    " не синхронизировано: " + errorCode.getErrorMessage() + " (в \"Прочие\" добавлен файл формы завершения)",
                                            sdf.format(System.currentTimeMillis()), random + "");
                                }
                            }
                        } else {
                            errors++;
                            logsTable.add("2", "Завершение работы " + "\"" + work.getName() + "\"" +
                                    ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                        }
                    }
                }
            }
        }
    }

    /**
     * Завершение работ с формой завершения комментарий
     */
    private void finishedCommentsWork() {
        List<OfflineCompletionWorkComment> works = addCompletionComment.get();
        if (works != null) {
            for (OfflineCompletionWorkComment work : works) {
                if (errors < 6) {
                    String result = finishWork(work.getActionID(), null, null, "COMMENT", work.getComment(), null, null);
                    if (result != null) {
                        ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                        if (errorCode != null) {
                            if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                                logsTable.add("1", "Завершение работы " + "\"" + work.getName() + "\"" +
                                        " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                            } else {
                                // добавляем коммент в случае неуспешной
                                AddCommentRequest addComment = new AddCommentRequest();
                                addComment.setPerson(person);
                                addComment.setWorkID(work.getActionID());
                                addComment.setCommentText(work.getComment());
                                addComment.setCommentType(CommentConst.WORK);
                                String resultComment = addComment.addComment();
                                ItemResult itemResult = RestClient.getGson().fromJson(resultComment, ItemResult.class);
                                if (itemResult != null) {
                                    if (itemResult.getResult().equals(Wrapper.NO_ERROR)) {
                                        logsTable.add("3", "Завершение работы " + "\"" + work.getName() + "\"" +
                                                        " не синхронизировано: " + errorCode.getErrorMessage() + " (комментарий добавлен к работе как обычный)",
                                                sdf.format(System.currentTimeMillis()), random + "");
                                    } else {
                                        logsTable.add("3", "Завершение работы " + "\"" + work.getName() + "\"" +
                                                        " не синхронизировано: " + errorCode.getErrorMessage() + " (комментарий не добавлен к работе)",
                                                sdf.format(System.currentTimeMillis()), random + "");
                                    }
                                }
                            }
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Завершение работы " + "\"" + work.getName() + "\"" +
                                ": ошибка синхронизации", sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Завершение работ с формой завершения процесс
     */
    private void finishedProcessInfoWorks() {
        List<FinishProcessWorkItem> finishProcessWorkItems = addFinishProcess.get();
        if (finishProcessWorkItems != null) {
            for (FinishProcessWorkItem finishProcessWorkItem : finishProcessWorkItems) {
                if (errors < 6) {
                    FinishProcess finishProcess = new FinishProcess();
                    finishProcess.setPerson(person);
                    finishProcess.setActivity(null);
                    finishProcess.setActionID(finishProcessWorkItem.getActionID());
                    finishProcess.setProcInstID(finishProcessWorkItem.getProcInstID());
                    finishProcess.setSignal(finishProcessWorkItem.getSignal());
                    finishProcess.setComment(finishProcessWorkItem.getComment());
                    finishProcess.setAddSignature(finishProcessWorkItem.isAddSignature());
                    finishProcess.setRawData(finishProcessWorkItem.getRawdata());
                    String result = finishProcess.finish();
                    ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                    if (errorCode != null) {
                        if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                            logsTable.add("1", "Завершение работы " + "\"" + finishProcessWorkItem.getName() +
                                    "\"" + " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                        } else {
                            logsTable.add("3", "Завершение работы " + "\"" + finishProcessWorkItem.getName() + "\"" +
                                    " не синхронизировано " + errorCode.getErrorMessage(), sdf.format(System.currentTimeMillis()), random + "");
                        }
                    } else {
                        errors++;
                        logsTable.add("2", "Завершение работы " + "\"" + finishProcessWorkItem.getName() + "\"" +
                                " синхронизировано", sdf.format(System.currentTimeMillis()), random + "");
                    }
                }
            }
        }
    }

    /**
     * Метод завершает работу с формой завершения "Файл"
     * При успешной отправке запроса метод возвращает строку в формате json
     * Иначе - возвращает null
     *
     * @return - результат запроса в формате json
     */
    public String finishWork(String workID, String fileName, String fileIdentifier, String typeFinishedWork,
                             String comment, String tmp_file_path, String type) {

        try {

            URL url = new URL(person.getHost() + "rest/api/workflow/work/set_result");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json; charset=utf-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String basicAuth = "Basic " + new String(Base64.encode(person.getAuth().getBytes(), Base64.NO_WRAP));
            conn.setRequestProperty("Authorization", basicAuth);

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            DataOutputStream request = new DataOutputStream(conn.getOutputStream());

            request.writeBytes("workID=" + URLEncoder.encode(workID, "utf-8") + "&");

            if (typeFinishedWork.equals("FILE")) {
                request.writeBytes("completionForm=" + URLEncoder.encode("FILE", "utf-8") + "&");
                request.writeBytes("type=" + URLEncoder.encode(type, "utf-8") + "&");
                request.writeBytes("file_name=" + URLEncoder.encode(fileName, "utf-8") + "&");
                if (tmp_file_path != null) {
                    request.writeBytes("file_path=" + URLEncoder.encode(tmp_file_path, "utf-8") + "&");
                } else if (fileIdentifier != null) {
                    request.writeBytes("file_identifier=" + URLEncoder.encode(fileIdentifier, "utf-8") + "&");
                }
                request.writeBytes("locale=" + URLEncoder.encode(MyApplication.getLang(), "utf-8") + "&");
            } else if (typeFinishedWork.equals("COMMENT")) {
                request.writeBytes("completionForm=" + URLEncoder.encode("COMMENT", "utf-8") + "&");
                request.writeBytes("comment=" + URLEncoder.encode(comment, "utf-8") + "&");
            }

            request.flush();
            request.close();

            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();

            return response.toString();

        } catch (Exception e) {
            return null;
        }
    }
}
