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

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.devspark.appmsg.AppMsg;
import com.pnikosis.materialishprogress.ProgressWheel;

import org.json.JSONObject;

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.CustomImageView;
import kz.arta.synergy.workflow.mobile.android.common.models.ErrorCode;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.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.MyApplication;
import kz.arta.synergy.workflow.mobile.android.common.utils.Wrapper;
import kz.arta.synergy.workflow.mobile.android.forms.general.activities.FormPlayer;
import kz.arta.synergy.workflow.mobile.android.forms.mobile.FormUtils;
import kz.arta.synergy.workflow.mobile.android.forms.mobile.components.MobileFormView;
import kz.arta.synergy.workflow.mobile.android.forms.mobile.manager.MobileFormJson;
import kz.arta.synergy.workflow.mobile.android.forms.mobile.manager.SaveFormData;
import kz.arta.synergy.workflow.mobile.android.forms.mobile.models.FormData;

/**
 * Created by neox on 16.07.15.
 * Нативный просмотрщик форм
 */
public class FormPlayerNative extends Activity {

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

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

    /**
     * Авторизированный пользователь
     */
    private Person person;

    /**
     * Контейнер, в котором находится форма
     */
    private LinearLayout formLayout;

    /**
     * UUID формы
     */
    private String formUUID;

    /**
     * UUID данных по форме
     */
    private String dataUUID;

    /**
     * Идентификатор файла по форме
     */
    private String fileUUID;

    /**
     * Просмоторщик форм
     */
    private MobileFormView mobileFormView;

    /**
     * Элементы меню
     */
    private String[] items;

    /**
     * Можно ли редактировать текущую форму
     */
    private boolean canEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

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

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

        items = new String[2];
        items[0] = getString(R.string.full_version);
        items[1] = getString(R.string.information);

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        dataUUID = intent.getStringExtra(ActivityConst.DATA_UUID);
        fileUUID = intent.getStringExtra(ActivityConst.FILE_IDENTIFIER);
        canEdit = Boolean.parseBoolean(getIntent().getStringExtra(ActivityConst.CAN_EDIT));

        if (dataUUID != null) {
            getFormUUID();
        }
    }

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

        // кнопка сохранить
        CustomImageView saveButton = (CustomImageView) findViewById(R.id.form_player_activity_button_save);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mobileFormView.isValid()) {
                    AppMsg.makeText(activity, getString(R.string.mandatory_fields), AppMsg.STYLE_ALERT).show();
                    return;
                }
                // сохранение данных по форме
                saveFormData(false);
            }
        });

        // кнопка меню
        CustomImageView menuButton = (CustomImageView) findViewById(R.id.form_player_activity_button_menu);
        menuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
                dialog.setTitle(getResources().getString(R.string.menu));
                dialog.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int index) {
                        switch (index) {
                            case 0:
                                changePlayer();
                                break;
                            case 1:
                                getFormInfo();
                                break;
                        }
                    }
                });
                dialog.show();
            }
        });

        // контейнер, в котором будет находиться форма
        formLayout = (LinearLayout) findViewById(R.id.form_view_layout);

        // получение данных по форме
        new MobileFormJson(formUUID, dataUUID, person) {
            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                if (result == null) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                    return;
                }
                // и отрисовываются компоненты формы
                mobileFormView = new MobileFormView(activity, formLayout, result);
                super.onPostExecute(result);
            }
        }.execute();

        // кнопка готово
        Button save = (Button) findViewById(R.id.form_view_button);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mobileFormView.isValid()) {
                    AppMsg.makeText(activity, getString(R.string.mandatory_fields), AppMsg.STYLE_ALERT).show();
                    return;
                }
                // сохранение данных по форме
                saveFormData(true);
            }
        });
    }

    /**
     * Метод открывает нативный просмотрщик
     */
    private void changePlayer() {
        Intent intent = new Intent(activity, FormPlayer.class);
        intent.putExtra(ActivityConst.DATA_UUID, dataUUID);
        intent.putExtra(ActivityConst.PERSON, person);
        intent.putExtra(ActivityConst.CAN_EDIT, String.valueOf(canEdit));
        startActivityForResult(intent, ActionUtils.SAVE_FORM);
        finish();
    }

    /**
     * Метод получает идентификатор формы
     */
    private void getFormUUID() {
        new SendGetRequest("rest/api/asforms/data/" + dataUUID + "?locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                    progressBar.setVisibility(View.GONE);
                    return;
                }
                try {
                    formUUID = RestClient.getGson().fromJson(result, FormData.class).form;
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                    progressBar.setVisibility(View.GONE);
                    return;
                }
                if (formUUID != null) {
                    init();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод сохраняет данные по форме
     */
    private void saveFormData(final boolean close) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Void... params) {
                return new SaveFormData(person, formUUID, dataUUID, FormUtils.getFormData(formLayout)).saveForm(true);
            }

            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                if (result == null) {
                    AppMsg.makeText(activity, getString(R.string.error_to_get_save_form_data), AppMsg.STYLE_ALERT).show();
                    return;
                }
                try {
                    ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                    if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                        AppMsg.makeText(activity, getString(R.string.data_saved), AppMsg.STYLE_INFO).show();
                        if (close) {
                            Intent intent = new Intent();
                            intent.putExtra(ActivityConst.FORM_ID, formUUID);
                            intent.putExtra(ActivityConst.DATA_UUID, dataUUID);
                            intent.putExtra(ActivityConst.FILE_IDENTIFIER, fileUUID);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                        }
                    } else {
                        AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                    }
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_to_get_save_form_data), AppMsg.STYLE_ALERT).show();
                    return;
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Получение информации о форме
     */
    private void getFormInfo() {
        new SendGetRequest("rest/api/asforms/form/" + formUUID, person) {
            @Override
            protected void onPostExecute(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    String formName = object.getString("name");
                    AlertDialog.Builder alert = new AlertDialog.Builder(activity);
                    alert.setTitle(R.string.information);
                    alert.setMessage(formName);
                    alert.setPositiveButton(R.string.ok, null);
                    alert.show();
                } catch (Exception ignored) {
                }
                super.onPostExecute(result);
            }
        }.execute();
    }
}
