package kz.arta.synergy.workflow.mobile.android.works.activities.send;

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.AsyncTask;
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 com.google.gson.JsonSyntaxException;
import com.pnikosis.materialishprogress.ProgressWheel;

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.requests.RestClient;
import kz.arta.synergy.workflow.mobile.android.common.requests.SendGetRequest;
import kz.arta.synergy.workflow.mobile.android.common.utils.ActionUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.DateUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.Logger;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
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.users.activities.UserChooserActivity;
import kz.arta.synergy.workflow.mobile.android.users.activities.UserChooserMultiActivity;
import kz.arta.synergy.workflow.mobile.android.works.manager.send.SendWork;
import kz.arta.synergy.workflow.mobile.android.works.models.SendWorkData;

/**
 * Created by neox on 19.04.14.
 * Отправка работы на согласование/ознакомление/утверждение, перепоручение работы
 */
public class SendWorkActivity extends FragmentActivity {

    /**
     * Для открытыия экрана с выбором исполнителей
     */
    public static final int SELECT_RES_USERS = 1;

    /**
     * Для открытыия экрана с выбором ответственного
     */
    public static final int SELECT_RES_USER = 2;

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

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

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

    /**
     * Текст работы
     */
    private EditText workName;

    /**
     * Кнопка "Отправить"
     */
    private Button sendButton;

    /**
     * Текствью "Дата завершения"
     */
    private TextView finishDate;

    /**
     * Текствью "Время завершения"
     */
    private TextView finishTime;

    /**
     * Данные для отправки запроса
     */
    private SendWorkData sendWorkData;

    /**
     * Формы завершения (при перепоручении)
     */
    private String[] itemsWorkCompletion;

    /**
     * Форма завершения (при перепоручении)
     */
    private TextView formCompletionName;

    /**
     * UUID выбранной формы завершения (если пользователь выбрал перепоручить)
     */
    private String formCompletionID;

    /**
     * UUID ответственного за работу
     */
    private String responsibleID;

    /**
     * Чекбокс для выбора ответственного
     */
    private CheckBox resCheckBox;

    /**
     * Поле ответственный
     */
    private TextView textViewResponsible;

    /**
     * Поле исполнители
     */
    private TextView textViewResUsers;

    /**
     * UUID работы по которой запускается маршрут
     */
    private String workID;

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

    /**
     * Тип действия
     */
    private String actionType;

    /**
     * Тип операции
     */
    private String operationType;

    /**
     * Тип процесса
     */
    private String type;

    /**
     * Идентификаторы выбранных пользователей
     */
    private List<String> selectedUsers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

        sendWorkData = new SendWorkData();

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
            ((TextView) findViewById(R.id.title_action_bar_send)).setTypeface(Fonts.getMedium(activity));
        }

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

        // получаем интент
        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        actionType = intent.getStringExtra(ActivityConst.ACTION_TYPE);
        operationType = intent.getStringExtra(ActivityConst.OPERATION_TYPE);
        type = intent.getStringExtra(ActivityConst.TYPE);
        workID = intent.getStringExtra(ActivityConst.WORK_ID);
        documentID = intent.getStringExtra(ActivityConst.DOCUMENT_ID);

        Logger.v("WORKID = " + workID);
        Logger.v("DOCUMENTID = " + documentID);

        sendWorkData.setType(type);
        if (workID != null) {
            sendWorkData.setWorkID(workID);
        } else if (documentID != null) {
            sendWorkData.setDocumentID(documentID);
        }

        // если пользователь хочет перепоручить работу - создаем нужные компоненты
        if (type != null && type.equals("3")) {
            String formID = intent.getStringExtra(ActivityConst.FORM_ID);
            if (formID != null) {
                sendWorkData.setCompletionFormID(formID);
            }
            initReassignComponents(formID);
            ((TextView) findViewById(R.id.send_work_title_users)).setText(getString(R.string.choose_executor));
            (findViewById(R.id.send_work_checkbox_layout)).setVisibility(View.VISIBLE);
        }

        // создаем основные компоненты
        initComponents();

        // и грузим данные для экрана
        new GetParams().execute();
    }

    /**
     * Инициализация компонентов если перепоручаем работы
     *
     * @param formID - uuid формы завершения
     */
    private void initReassignComponents(String formID) {
        // заголовок выбора ответственного
        final TextView titleResponsible = (TextView) findViewById(R.id.send_work_responsible_title);
        titleResponsible.setVisibility(View.VISIBLE);
        titleResponsible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resCheckBox.setChecked(!resCheckBox.isChecked());
            }
        });
        // чекбокс для выбора ответственного
        resCheckBox = (CheckBox) findViewById(R.id.send_work_check_box);
        resCheckBox.setTypeface(Fonts.getMedium(activity));
        resCheckBox.setVisibility(View.VISIBLE);
        resCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    textViewResponsible.setText("");
                    responsibleID = null;
                }
            }
        });
        // ответственный
        textViewResponsible = (TextView) findViewById(R.id.send_work_responsible);
        textViewResponsible.setTypeface(Fonts.getMedium(activity));
        textViewResponsible.setVisibility(View.VISIBLE);
        textViewResponsible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (resCheckBox.isChecked()) {
                    Intent intent = new Intent(SendWorkActivity.this, UserChooserActivity.class);
                    intent.putExtra(ActivityConst.PERSON, person);
                    intent.putExtra(ActivityConst.SHOW_ALL, person.getSettings().getAllowResendWork());
                    intent.putExtra(ActivityConst.USER_ID, responsibleID);
                    intent.putExtra(ActivityConst.USER_NAME, textViewResponsible.getText());
                    startActivityForResult(intent, SELECT_RES_USER);

                }
            }
        });
        // форма завершения
        formCompletionName = (TextView) findViewById(R.id.send_work_form_completion);
        // если нет форм завершения - не отображаем список
        if (person.getSettings().getWorkCompletionForms().length == 0) {
            (findViewById(R.id.send_work_form_completion_title)).setVisibility(View.GONE);
            formCompletionName.setVisibility(View.GONE);
        } else {
            (findViewById(R.id.send_work_form_completion_title)).setVisibility(View.VISIBLE);
            // форма завершения
            formCompletionName.setVisibility(View.VISIBLE);
            formCompletionName.setTypeface(Fonts.getMedium(activity));
            if (formID != null) {
                if (formID.length() == 0) {
                    formCompletionName.setText(getString(R.string.no));
                } else {
                    formCompletionName.setText(Utils.getFormCompletion(formID, person, activity, false));
                }
            }
            formCompletionName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    builder.setTitle(getString(R.string.form_completion));
                    final CompletionFormItem[] completionForms = person.getSettings().getWorkCompletionForms();
                    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.no)), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (item == 0) {
                                formCompletionID = null;
                                formCompletionName.setText(getString(R.string.no));
                                sendWorkData.setCompletionFormID(null);
                            } else {
                                formCompletionID = completionForms[item - 1].getId();
                                formCompletionName.setText(itemsWorkCompletion[item - 1]);
                                sendWorkData.setCompletionFormID(formCompletionID);
                            }
                        }
                    });
                    builder.setCancelable(true);
                    builder.show();
                }
            });
        }
    }

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

        workName = (EditText) findViewById(R.id.send_work_text_work);

        textViewResUsers = (TextView) findViewById(R.id.send_work_users);
        textViewResUsers.setTypeface(Fonts.getMedium(activity));
        textViewResUsers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SendWorkActivity.this, UserChooserMultiActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.SHOW_ALL, true);
                if (type.equals(ActionUtils.REASSIGN)) {
                    if (person.getSettings().getAllowAddWorkResponsibles().equals("true")) {
                        intent.putExtra(ActivityConst.SHOW_ALL, person.getSettings().getAllowAddWorkResponsibles());
                    } else {
                        intent.putExtra(ActivityConst.SHOW_ALL, "false");
                    }
                } else {
                    intent.putExtra(ActivityConst.SHOW_ALL, "true");
                }
                if (person.getSettings().getSetWorkFromResponsible().equals("true")) {
                    intent.putExtra(ActivityConst.USER_ID, responsibleID);
                }
                if (selectedUsers != null && selectedUsers.size() != 0) {
                    intent.putExtra(ActivityConst.SELECTED, selectedUsers.toArray(new String[selectedUsers.size()]));
                }
                startActivityForResult(intent, SELECT_RES_USERS);

            }
        });

        finishDate = (TextView) findViewById(R.id.send_work_finish_data);
        finishDate.setTypeface(Fonts.getMedium(activity));
        finishDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePicker(finishDate);
            }
        });

        finishTime = (TextView) findViewById(R.id.send_work_finish_time);
        finishTime.setTypeface(Fonts.getMedium(activity));
        finishTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker(finishTime);
            }
        });

        sendButton = (Button) findViewById(R.id.send_work_send);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type != null && type.equals(ActionUtils.REASSIGN)) {
                    if (!resCheckBox.isChecked() && TextUtils.isEmpty(textViewResUsers.getText()) && TextUtils.isEmpty(textViewResponsible.getText())) {
                        AppMsg.makeText(activity, getString(R.string.cannot_create_work), AppMsg.STYLE_ALERT).show();
                        return;
                    } else if (resCheckBox.isChecked() && TextUtils.isEmpty(textViewResUsers.getText()) && TextUtils.isEmpty(textViewResponsible.getText())) {
                        AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                        return;
                    }
                    if (resCheckBox.isChecked()) {
                        sendWorkData.setResUserID(responsibleID);
                    }
                } else {
                    if (TextUtils.isEmpty(textViewResUsers.getText())) {
                        AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                        return;
                    }
                }
                // если заполнены все поля
                if (!TextUtils.isEmpty(workName.getText())) {
                    progressBar.setVisibility(View.VISIBLE);
                    String fnDate = DateUtils.parseData(finishDate.getText().toString() + " " + finishTime.getText().toString(),
                            DateUtils.DEFAULT_DATE_FORMAT, DateUtils.DEFAULT_EDIT_TEXT_DATE + " " + DateUtils.DEFAULT_EDIT_TEXT_TIME);
                    sendWorkData.setName(workName.getText().toString());
                    sendWorkData.setFinishDate(fnDate);
                    // отправляем работу
                    SendWork sendWork = new SendWork();
                    sendWork.setActivity(activity);
                    sendWork.setPerson(person);
                    sendWork.setSendWorkData(sendWorkData);
                    sendWork.setProgressBar(progressBar);
                    sendWork.execute();
                } else {
                    AppMsg.makeText(activity, getString(R.string.empty_edit), AppMsg.STYLE_ALERT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SELECT_RES_USERS && resultCode != RESULT_CANCELED) {
            UserSerializable userSerializable = (UserSerializable) data.getSerializableExtra(ActivityConst.USERS_ID);
            List<String> names = userSerializable.getNames();
            selectedUsers = userSerializable.getUsersID();
            textViewResUsers.setText(names.toString().replace("[", "").replace("]", ""));
            sendWorkData.setUsers(selectedUsers);
        } else if (requestCode == SELECT_RES_USER && resultCode != RESULT_CANCELED) {
            String userName = data.getStringExtra(ActivityConst.USER_NAME);
            responsibleID = data.getStringExtra(ActivityConst.USER_ID);
            textViewResponsible.setText(userName);
            sendWorkData.setUsers(selectedUsers);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Откывает диалог выбора даты
     *
     * @param edit - TextView
     */
    private void showDatePicker(final TextView edit) {
        DatePickerFragment date = new DatePickerFragment();
        Bundle args = new Bundle();
        args.putInt(DateUtils.YEAR, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                DatePickerFragment.YEAR, DateUtils.DEFAULT_EDIT_TEXT_DATE)));
        args.putInt(DateUtils.MONTH, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                DatePickerFragment.MONTH, DateUtils.DEFAULT_EDIT_TEXT_DATE)) - 1);
        args.putInt(DateUtils.DAY, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                DatePickerFragment.DAY, DateUtils.DEFAULT_EDIT_TEXT_DATE)));
        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)
                        + " / " + String.valueOf(year));
            }
        });
        date.show(getSupportFragmentManager(), null);
    }

    /**
     * Открывает диалог выбора времени
     *
     * @param edit - TextView
     */
    private void showTimePicker(final TextView edit) {
        TimePickerFragment date = new TimePickerFragment();
        Bundle args = new Bundle();
        args.putInt(DateUtils.HOUR, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                TimePickerFragment.HOURS, DateUtils.DEFAULT_EDIT_TEXT_TIME)));
        args.putInt(DateUtils.MINUTES, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                TimePickerFragment.MINUTES, DateUtils.DEFAULT_EDIT_TEXT_TIME)));
        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);
    }

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

    /**
     * Отправляет запрос на получение описания экрана
     */
    class GetParams extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPostExecute(String result) {
            if (result == null) {
                AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                return;
            }
            ScreenInfo screenInfo;
            try {
                screenInfo = RestClient.getGson().fromJson(result, ScreenInfo.class);
                workName.setText(screenInfo.name);
                sendButton.setText(screenInfo.button_name);
                finishDate.setText(DateUtils.parseData(screenInfo.finish_date,
                        DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
                finishTime.setText(DateUtils.parseData(screenInfo.finish_date,
                        DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
                sendWorkData.setFinishDate(screenInfo.finish_date);
            } catch (JsonSyntaxException exc) {
                AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
            }
            progressBar.setVisibility(View.GONE);
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            if (workID != null && documentID != null) {
                if (type.equals(ActionUtils.REASSIGN)) {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?documentID="
                            + documentID + "&actionType=REASSIGN&locale=" + MyApplication.getLang());
                } else {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?documentID="
                            + documentID + "&actionType=" + actionType + "&operationType=" + operationType + "&locale=" + MyApplication.getLang());
                }
            } else if (workID != null) {
                if (type.equals(ActionUtils.REASSIGN)) {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?workID="
                            + workID + "&actionType=REASSIGN&locale=" + MyApplication.getLang());
                } else {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?workID="
                            + workID + "&actionType=" + actionType + "&operationType=" + operationType + "&locale=" + MyApplication.getLang());
                }
            } else {
                if (type.equals(ActionUtils.REASSIGN)) {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?documentID="
                            + documentID + "&actionType=REASSIGN&locale=" + MyApplication.getLang());
                } else {
                    return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?documentID="
                            + documentID + "&actionType=" + actionType + "&operationType=" + operationType + "&locale=" + MyApplication.getLang());
                }
            }
        }
    }

    class ScreenInfo {

        /**
         * Имя работы
         */
        String name;

        /**
         * Дата завершения
         */
        String finish_date;

        /**
         * Имя кнопки
         */
        String button_name;

    }
}
