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

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import com.devspark.appmsg.AppMsg;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.common.ActivityConst;
import kz.arta.synergy.workflow.mobile.android.common.components.DatePickerFragment;
import kz.arta.synergy.workflow.mobile.android.common.components.TimePickerFragment;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.models.settings.CompletionFormItem;
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.UserSerializable;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.documents.resolution.ResolutionConst;
import kz.arta.synergy.workflow.mobile.android.documents.resolution.models.ItemResolution;
import kz.arta.synergy.workflow.mobile.android.documents.resolution.models.ResolutionWorkType;
import kz.arta.synergy.workflow.mobile.android.users.activities.UserChooserActivity;
import kz.arta.synergy.workflow.mobile.android.users.activities.UserChooserMultiActivity;

/**
 * Created by neox on 15.09.14.
 * Экран для добавления нового пункта резолюции
 */
public class AddResolutionActivity extends FragmentActivity {

    /**
     * Пользователь
     */
    private Person person;

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

    /**
     * Переклюачатель "Ответственный"
     */
    private CheckBox responsibleCheckBox;

    /**
     * Имя пункта резолюции
     */
    private EditText nameItem;

    /**
     * Ответственный
     */
    private TextView responsible;

    /**
     * Исполнители
     */
    private TextView executors;

    /**
     * Тип резолюции
     */
    private TextView typeResolution;

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

    /**
     * Дата завершения
     */
    private TextView finishDate;

    /**
     * Время завершения
     */
    private TextView finishTime;

    /**
     * Заголовок для чекбокса "Ответственный"
     */
    private TextView titleCheckBox;

    /**
     * Заголовок для поля "Форма завершения"
     */
    private TextView titleFormCompletion;

    /**
     * Заголовок для поля "Завершение"
     */
    private TextView titleCompletion;

    /**
     * Текущий элемент резолюции (используется при редактировании)
     */
    private ItemResolution itemResolution;

    /**
     * Номер редактируемого элемента резолюции в основном списке
     */
    private String item;

    /**
     * Идентификатор ответственного
     */
    private String responsibleID;

    /**
     * Идентификатор формы заврешения
     */
    private String formCompletionID;

    /**
     * Список исполнителей
     */
    private List<ItemResolution.ResolutionsUsers> userArray = new ArrayList<>();

    /**
     * Был бы выбран тип "Отправка документа"
     */
    private boolean checkedSendDocument;

    /**
     * Принята ли текущая резолюция
     */
    private int completed;

    /**
     * Идентификаторы выбранных исполнителей (через юзерчузер)
     */
    private List<String> selectedUsers = new ArrayList<>();

    /**
     * Максимальная дата пункта резолюции
     */
    private String maxFinishDate;

    /**
     * Идентификатор процесса для текущего пункта
     */
    private String currentDictID;

    /**
     * Название процесса для текущего пункта
     */
    private String currentProcess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

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

        activity = this;
        person = (Person) getIntent().getSerializableExtra(ActivityConst.PERSON);
        itemResolution = (ItemResolution) getIntent().getSerializableExtra(ActivityConst.RESOLUTION_ITEM);
        item = (String) getIntent().getSerializableExtra(ActivityConst.ITEM_NUMBER);
        completed = getIntent().getIntExtra(ActivityConst.STATUS, 0);
        maxFinishDate = getIntent().getStringExtra(ActivityConst.MAX_FINISH_DATE);

        initGeneralComponents();
        checkItemResolution();
    }

    /**
     * Инициализация основных компонентов
     */
    private void initGeneralComponents() {

        currentProcess = person.getSettings().getResolutionWorkType()[0].getItemProcess();

        currentDictID = person.getSettings().getResolutionWorkType()[0].getDictID();

        titleFormCompletion = (TextView) findViewById(R.id.add_resolution_form_completion_title);
        titleCompletion = (TextView) findViewById(R.id.add_resolution_change_period_title);

        // формулировка пункта
        nameItem = (EditText) findViewById(R.id.add_resolution_text);

        // checkbox ответственного
        responsibleCheckBox = (CheckBox) findViewById(R.id.add_resolution_check_box);
        responsibleCheckBox.setTypeface(Fonts.getMedium(activity));
        responsibleCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                responsible.setText("");
                responsibleID = null;
            }
        });

        titleCheckBox = (TextView) findViewById(R.id.add_resolution_check_box_title);
        titleCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((currentProcess.equals(ResolutionConst.ASSIGNMENT) || currentProcess.equals(ResolutionConst.RESOLUTION)) && completed != 1) {
                    responsibleCheckBox.setChecked(!responsibleCheckBox.isChecked());
                }
            }
        });

        // ответственный
        responsible = (TextView) findViewById(R.id.add_resolution_responsible);
        responsible.setTypeface(Fonts.getMedium(activity));
        responsible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (responsibleCheckBox.isChecked()) {
                    Intent intent = new Intent(activity, UserChooserActivity.class);
                    intent.putExtra(ActivityConst.PERSON, person);
                    intent.putExtra(ActivityConst.SHOW_ALL, person.getSettings().getAllowAddWorkResponsibles());
                    intent.putExtra(ActivityConst.USER_ID, responsibleID);
                    intent.putExtra(ActivityConst.USER_NAME, responsible.getText());
                    startActivityForResult(intent, ResolutionConst.SELECT_RESPONSIBLE);
                }
            }
        });

        // исполнители
        executors = (TextView) findViewById(R.id.add_resolution_executors);
        executors.setTypeface(Fonts.getMedium(activity));
        executors.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, UserChooserMultiActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                if (person.getSettings().getAllowAddWorkResponsibles().equals("true")) {
                    intent.putExtra(ActivityConst.SHOW_ALL, person.getSettings().getAllowAddWorkResponsibles());
                } else if (person.getSettings().getSetWorkFromResponsible().equals("true")) {
                    intent.putExtra(ActivityConst.SHOW_ALL, person.getSettings().getSetWorkFromResponsible());
                } else {
                    intent.putExtra(ActivityConst.SHOW_ALL, "false");
                }
                if (person.getSettings().getSetWorkFromResponsible().equals("true")) {
                    intent.putExtra(ActivityConst.USER_ID, responsibleID);
                }
                if (!selectedUsers.isEmpty()) {
                    intent.putExtra(ActivityConst.SELECTED, selectedUsers.toArray(new String[selectedUsers.size()]));
                }
                startActivityForResult(intent, ResolutionConst.SELECT_EXECUTORS);
            }
        });

        // дата завершения
        finishDate = (TextView) findViewById(R.id.add_resolution_finish_date);
        finishDate.setTypeface(Fonts.getMedium(activity));
        if (person.getDefaults().getShow_resolution_date().equals("true") && !currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
            finishDate.setText(DateUtils.parseData(person.getDefaults().getFinish_date(),
                    DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
        }
        finishDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePicker(finishDate);
            }
        });

        // время завершения
        finishTime = (TextView) findViewById(R.id.add_resolution_finish_time);
        finishTime.setTypeface(Fonts.getMedium(activity));
        if (person.getDefaults().getShow_resolution_date().equals("true") && !currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
            finishTime.setText(DateUtils.parseData(person.getDefaults().getFinish_date(),
                    DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
        }
        finishTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker(finishTime);
            }
        });

        // тип работы
        typeResolution = (TextView) findViewById(R.id.add_resolution_type);
        typeResolution.setText(person.getSettings().getResolutionWorkType()[0].getItemName());
        typeResolution.setTypeface(Fonts.getMedium(activity));
        typeResolution.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialogTypeWork();
            }
        });

        // форма завершения
        formCompletion = (TextView) findViewById(R.id.add_resolution_form_completion);
        formCompletion.setTypeface(Fonts.getMedium(activity));
        formCompletion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialogFormCompletion();
            }
        });

        // кнопка "Готово"
        Button finished = (Button) findViewById(R.id.add_resolution_button_save);
        finished.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(nameItem.getText())) {
                    AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                    return;
                }
                if (itemResolution != null) {
                    boolean found = false;
                    for (ResolutionWorkType type : person.getSettings().getResolutionWorkType()) {
                        if (type.getDictID().equals(itemResolution.getDictID())) {
                            found = true;
                        }
                    }
                    if (!found) {
                        AppMsg.makeText(activity, getString(R.string.resolution_type_not_found), AppMsg.STYLE_ALERT).show();
                        return;
                    }
                }
                if (!currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
                    if (TextUtils.isEmpty(finishDate.getText()) || TextUtils.isEmpty(finishTime.getText())) {
                        AppMsg.makeText(activity, getString(R.string.incorrect_finish_date), AppMsg.STYLE_ALERT).show();
                        return;
                    }
                    Calendar currentDate = Calendar.getInstance();
                    Calendar itemDate = Calendar.getInstance();
                    currentDate.setTime(new Date(System.currentTimeMillis()));
                    itemDate.setTime(new Date(Long.parseLong(DateUtils.getMillisecondsFromDateResolution(finishDate.getText() + " " + finishTime.getText()))));
                    // проверяем чтобы текущий пункт резолюции не был меньше текущей даты
                    if (!itemDate.after(currentDate)) {
                        AppMsg.makeText(activity, getString(R.string.incorrect_finish_date), AppMsg.STYLE_ALERT).show();
                        return;
                    }
                    // также проверяем чтобы текущая дата завершения не была больше даты завершения документа (если в конфигураторе стоит галочка)
                    if (person.getSettings().getDateResolutionAfterFinishDocument().equals("false") && maxFinishDate != null) {
                        currentDate.setTime(new Date(Long.parseLong(DateUtils.getMillisecondsFromDate(maxFinishDate))));
                        itemDate.setTime(new Date(Long.parseLong(DateUtils.getMillisecondsFromDateResolution(finishDate.getText() + " " + "00:00:00"))));
                        if (itemDate.getTimeInMillis() > currentDate.getTimeInMillis()) {
                            AppMsg.makeText(activity, getString(R.string.date_item_resolution_after_document_message), AppMsg.STYLE_ALERT).show();
                            return;
                        }
                    }
                }
                if (completed == ResolutionConst.COMPLETED) {
                    if (itemResolution == null) {
                        finishedAddItem();
                    } else {
                        finishedChangeItem();
                    }
                } else {
                    if (currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
                        if (!TextUtils.isEmpty(executors.getText())) {
                            if (itemResolution == null) {
                                finishedAddItem();
                            } else {
                                finishedChangeItem();
                            }
                        } else {
                            AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                        }
                    } else {
                        if (!TextUtils.isEmpty(finishDate.getText()) && !TextUtils.isEmpty(finishTime.getText())) {
                            if (responsibleCheckBox.isChecked()) {
                                if (!TextUtils.isEmpty(responsible.getText())) {
                                    if (itemResolution == null) {
                                        finishedAddItem();
                                    } else {
                                        finishedChangeItem();
                                    }
                                } else {
                                    AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                                }
                            } else {
                                if (!TextUtils.isEmpty(executors.getText())) {
                                    if (itemResolution == null) {
                                        finishedAddItem();
                                    } else {
                                        finishedChangeItem();
                                    }
                                } else {
                                    AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                                }
                            }
                        } else {
                            AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                        }
                    }
                }
            }
        });
    }


    /**
     * Проверка редактируем ли мы пункт резолюции либо добавляем новый
     */
    private void checkItemResolution() {

        // для некоторых типов работ - отключаем необходимые компоненты
        if (currentProcess.equals(ResolutionConst.AGREEMENT) || currentProcess.equals(ResolutionConst.APPROVAL) ||
                currentProcess.equals(ResolutionConst.ACQUAINTANCE) || currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
            titleFormCompletion.setTextColor(getResources().getColor(R.color.disabled_title_all_activity));
            titleCheckBox.setTextColor(getResources().getColor(R.color.disabled_title_all_activity));
            formCompletion.setEnabled(false);
            formCompletion.setText(getString(R.string.work_result));
            formCompletionID = null;
            // исполнитель
            responsibleCheckBox.setEnabled(false);
            responsibleCheckBox.setChecked(false);
            responsible.setEnabled(false);
            responsible.setText("");
            responsibleID = null;
            // для пункта "Отправка документа" - отключаем время
            if (currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
                titleCompletion.setTextColor(getResources().getColor(R.color.disabled_title_all_activity));
                finishDate.setEnabled(false);
                finishDate.setText("");
                finishTime.setEnabled(false);
                finishTime.setText("");
            }
        }

        // если пользователь не редактирует существующй пункт резолюции - завершаем метод
        if (itemResolution == null) {
            return;
        }

        // идентификатор записи в справочнике (тип работы)
        currentDictID = itemResolution.getDictID();

        // идентификатор процесса (тип работы)
        currentProcess = Utils.getProcessByDictId(currentDictID, person);

        // имя
        nameItem.setText(itemResolution.getName());

        // ответственный
        responsibleID = itemResolution.getUserID();

        if (responsibleID == null) {
            responsibleCheckBox.setChecked(false);
            responsible.setText("");
        } else {
            responsible.setText(Utils.parseUser(itemResolution.getUser()));
        }

        // исполнители
        executors.setText(Utils.parseExecutors(itemResolution.getUsers()));
        if (itemResolution.getUsers() != null && itemResolution.getUsers().length != 0) {
            Collections.addAll(userArray, itemResolution.getUsers());
            for (ItemResolution.ResolutionsUsers user : userArray) {
                selectedUsers.add(user.getUserID());
            }
        }

        if (!currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
            // дата завершения
            finishDate.setText(DateUtils.parseData(DateUtils.getDateFromMilliseconds(itemResolution.getFinishdate().getDate()),
                    DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
            // время завершения
            finishTime.setText(DateUtils.parseData(DateUtils.getDateFromMilliseconds(itemResolution.getFinishdate().getDate()),
                    DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
        } else {
            finishDate.setText("");
            finishTime.setText("");
        }

        // форма завершения
        formCompletionID = itemResolution.getCompletionFormID();
        formCompletion.setText(Utils.getFormCompletion(itemResolution.getCompletionFormID(), person, activity, true));

        // текст текущего типа работы
        typeResolution.setText(itemResolution.getItemName());

        // если резолюция уже приянта - также отключаем необходимые компоненты
        if (completed == ResolutionConst.COMPLETED && itemResolution.getItemID() != null) {
            responsibleCheckBox.setEnabled(false);
            if (itemResolution.getUserID() == null || itemResolution.getUserID().isEmpty()) {
                responsibleCheckBox.setChecked(false);
            } else {
                responsibleCheckBox.setChecked(true);
                responsibleID = itemResolution.getUserID();
            }
            responsible.setText(itemResolution.getUser());
            responsible.setEnabled(false);
            typeResolution.setEnabled(false);
        }
    }

    /**
     * Метод закрывает активити в режиме добавления нового пункта
     */
    private void finishedAddItem() {
        Intent intent = new Intent();
        intent.putExtra(ActivityConst.RESOLUTION_ITEM, finished());
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * Метод возвращает объект класса ResolutionFinishDate (время завершения пункта резолюции)
     *
     * @return объект класса ResolutionFinishDate
     */
    private ItemResolution.ResolutionFinishDate getResolutionData() {
        ItemResolution.ResolutionFinishDate resolutionFinishDate = new ItemResolution.ResolutionFinishDate();
        resolutionFinishDate.setDate(DateUtils.getMillisecondsFromDateResolution(finishDate.getText() + " " + finishTime.getText()));
        return resolutionFinishDate;
    }

    /**
     * Метод закрывает активити в режиме добавления нового пункта
     */
    private void finishedChangeItem() {
        Intent intent = new Intent();
        intent.putExtra(ActivityConst.RESOLUTION_ITEM, finished());
        intent.putExtra(ActivityConst.ITEM_NUMBER, item);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * Метод строит пункт резолюции
     *
     * @return возвращает пункт резолюции
     */
    private ItemResolution finished() {

        // собираем объект
        ItemResolution item = new ItemResolution();
        item.setName(nameItem.getText().toString());

        if (responsibleID != null) {
            item.setUser(responsible.getText().toString());
            item.setUserID(responsibleID);
        }

        item.setUsers(userArray.toArray(new ItemResolution.ResolutionsUsers[userArray.size()]));
        item.setCompletionFormID(formCompletionID);
        item.setDictID(currentDictID);
        item.setItemName(typeResolution.getText().toString());

        if (!TextUtils.isEmpty(finishDate.getText()) && !TextUtils.isEmpty(finishTime.getText())) {
            item.setFinishdate(getResolutionData());
        } else {
            ItemResolution.ResolutionFinishDate resolutionFinishDate = new ItemResolution.ResolutionFinishDate();
            resolutionFinishDate.setDate(String.valueOf(System.currentTimeMillis()));
            item.setFinishdate(resolutionFinishDate);
        }

        if (currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
            item.setFinishdate(null);
        }

        // itemID
        if (itemResolution != null) {
            item.setItemID(itemResolution.getItemID());
        }
        return item;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ResolutionConst.SELECT_RESPONSIBLE && resultCode != RESULT_CANCELED) {
            String userName = data.getStringExtra(ActivityConst.USER_NAME);
            responsibleID = data.getStringExtra(ActivityConst.USER_ID);
            responsible.setText(userName);
            executors.setText("");
            selectedUsers.clear();
        } else if (requestCode == ResolutionConst.SELECT_EXECUTORS && resultCode != RESULT_CANCELED) {
            userArray.clear();
            selectedUsers.clear();
            UserSerializable userSerializable = (UserSerializable) data.getSerializableExtra(ActivityConst.USERS_ID);
            List<String> usersName = userSerializable.getNames();
            selectedUsers = userSerializable.getUsersID();
            if (usersName.isEmpty()) {
                return;
            }
            for (int i = 0; i < usersName.size(); i++) {
                ItemResolution.ResolutionsUsers resolutionsUsers = new ItemResolution.ResolutionsUsers();
                resolutionsUsers.setUserID(selectedUsers.get(i));
                resolutionsUsers.setUser(usersName.get(i));
                userArray.add(resolutionsUsers);
            }
            executors.setText(usersName.toString().replace("[", "").replace("]", ""));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Метод открывает диалог выбора даты
     *
     * @param edit - поле с датой
     */
    private void showDatePicker(final TextView edit) {
        DatePickerFragment date = new DatePickerFragment();
        Bundle args = new Bundle();
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        try {
            args.putInt(DateUtils.YEAR, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                    "yyyy", DateUtils.DEFAULT_EDIT_TEXT_DATE)));
        } catch (NumberFormatException e) {
            args.putInt(DateUtils.YEAR, c.get(Calendar.YEAR));
        }
        try {
            args.putInt(DateUtils.MONTH, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                    "MM", DateUtils.DEFAULT_EDIT_TEXT_DATE)) - 1);
        } catch (NumberFormatException e) {
            args.putInt(DateUtils.MONTH, c.get(Calendar.MONTH));
        }
        try {
            args.putInt(DateUtils.DAY, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                    "dd", DateUtils.DEFAULT_EDIT_TEXT_DATE)));
        } catch (NumberFormatException e) {
            args.putInt(DateUtils.DAY, c.get(Calendar.DAY_OF_MONTH));
        }
        date.setArguments(args);
        date.setCallBack(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                edit.setText(DateUtils.changePickerDialog(dayOfMonth) + " / " + DateUtils.changePickerDialog(monthOfYear + 1) + " / " + year);
            }
        });
        date.show(getSupportFragmentManager(), null);
    }

    /**
     * Метод открывает диалог выбора времени
     *
     * @param edit - поле с временем
     */
    private void showTimePicker(final TextView edit) {
        TimePickerFragment date = new TimePickerFragment();
        Bundle args = new Bundle();
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        try {
            args.putInt(DateUtils.HOUR, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                    "HH", DateUtils.DEFAULT_EDIT_TEXT_TIME)));
        } catch (NumberFormatException e) {
            args.putInt(DateUtils.HOUR, c.get(Calendar.HOUR));
        }
        try {
            args.putInt(DateUtils.MINUTES, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                    "mm", DateUtils.DEFAULT_EDIT_TEXT_TIME)));
        } catch (NumberFormatException e) {
            args.putInt(DateUtils.MINUTES, c.get(Calendar.MINUTE));
        }
        date.setArguments(args);
        date.setCallBack(new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                edit.setText(DateUtils.changePickerDialog(hour) + ":" + DateUtils.changePickerDialog(minute));
            }
        });
        date.show(getSupportFragmentManager(), null);
    }

    /**
     * Диалог выбора типа рабты
     */
    private void showDialogTypeWork() {
        final List<String> names = new ArrayList<>();
        for (ResolutionWorkType workType : person.getSettings().getResolutionWorkType()) {
            names.add(workType.getItemName());
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(getString(R.string.type_work_resolution));
        builder.setItems(names.toArray(new String[names.size()]), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                typeResolution.setText(names.get(item));
                currentDictID = person.getSettings().getResolutionWorkType()[item].getDictID();
                currentProcess = person.getSettings().getResolutionWorkType()[item].getItemProcess();
                if (itemResolution != null) {
                    itemResolution.setDictID(currentDictID);
                }
                if (currentProcess.equals(ResolutionConst.AGREEMENT) || currentProcess.equals(ResolutionConst.APPROVAL) ||
                        currentProcess.equals(ResolutionConst.ACQUAINTANCE) || currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
                    titleFormCompletion.setTextColor(getResources().getColor(R.color.disabled_title_all_activity));
                    titleCheckBox.setTextColor(getResources().getColor(R.color.disabled_title_all_activity));
                    formCompletion.setEnabled(false);
                    formCompletion.setText(getString(R.string.work_result));
                    formCompletionID = null;
                    executors.setText("");
                    executors.setEnabled(true);
                    userArray.clear();
                    selectedUsers.clear();
                    responsibleCheckBox.setEnabled(false);
                    responsibleCheckBox.setChecked(false);
                    responsible.setEnabled(false);
                    responsible.setText("");
                    responsibleID = null;
                    if (currentProcess.equals(ResolutionConst.SEND_DOCUMENT)) {
                        checkedSendDocument = true;
                        finishDate.setText("");
                        finishDate.setEnabled(false);
                        finishTime.setText("");
                        finishTime.setEnabled(false);
                        titleCompletion.setTextColor(getResources().getColor(R.color.disabled_title_all_activity));
                    } else {
                        if (person.getDefaults().getShow_resolution_date().equals("true")) {
                            finishDate.setText(DateUtils.parseData(person.getDefaults().getFinish_date(),
                                    DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
                        } else {
                            finishDate.setText("");
                        }
                        finishDate.setEnabled(true);
                        titleCompletion.setTextColor(getResources().getColor(R.color.default_text_color_titles));
                        if (person.getDefaults().getShow_resolution_date().equals("true")) {
                            finishTime.setText(DateUtils.parseData(person.getDefaults().getFinish_date(),
                                    DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
                        } else {
                            finishTime.setText("");
                        }
                        finishTime.setEnabled(true);
                    }
                } else if (currentProcess.equals(ResolutionConst.ASSIGNMENT) || currentProcess.equals(ResolutionConst.RESOLUTION)) {
                    titleFormCompletion.setTextColor(getResources().getColor(R.color.default_text_color_titles));
                    titleCompletion.setTextColor(getResources().getColor(R.color.default_text_color_titles));
                    titleCheckBox.setTextColor(getResources().getColor(R.color.default_text_color_titles));
                    formCompletion.setEnabled(true);
                    executors.setEnabled(true);
                    responsibleCheckBox.setEnabled(true);
                    responsible.setEnabled(true);
                    if (checkedSendDocument) {
                        if (person.getDefaults().getShow_resolution_date().equals("true")) {
                            finishDate.setText(DateUtils.parseData(person.getDefaults().getFinish_date(),
                                    DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
                        } else {
                            finishDate.setText("");
                        }
                        finishDate.setEnabled(true);
                        if (person.getDefaults().getShow_resolution_date().equals("true")) {
                            finishTime.setText(DateUtils.parseData(person.getDefaults().getFinish_date(),
                                    DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
                        } else {
                            finishTime.setText("");
                        }
                        finishTime.setEnabled(true);
                        checkedSendDocument = false;
                    }
                }
            }
        });
        builder.setCancelable(true);
        builder.show();
    }

    /**
     * Диалог выбора формы завершения
     */
    private void showDialogFormCompletion() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(getString(R.string.choose_form_end));
        final CompletionFormItem[] completionForms = person.getSettings().getWorkCompletionForms();
        final String[] itemsWorkCompletion = new String[completionForms.length];
        for (int i = 0; i < itemsWorkCompletion.length; i++) {
            itemsWorkCompletion[i] = completionForms[i].getName();
        }
        builder.setItems(Utils.parseFormCompletion(itemsWorkCompletion, getString(R.string.work_result)), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (item == 0) {
                    formCompletionID = null;
                    formCompletion.setText(getString(R.string.result));
                } else {
                    formCompletionID = completionForms[item - 1].getId();
                    formCompletion.setText(itemsWorkCompletion[item - 1]);
                }
            }
        });
        builder.setCancelable(true);
        builder.show();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}