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

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

import com.devspark.appmsg.AppMsg;
import com.google.gson.JsonSyntaxException;
import com.pnikosis.materialishprogress.ProgressWheel;

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.AButton;
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.Fonts;
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.works.models.WorkActionsItem;

/**
 * Created by neox on 02.03.15.
 * Экран для завершения работы процессом резолюция
 */
public class ActionResolutionActivity extends Activity {

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

    /**
     * Текущее активити
     */
    private Activity activity;

    /**
     * UUID работы с которой работаем
     */
    private String workID;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

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

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        workID = intent.getStringExtra(ActivityConst.WORK_ID);

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

        getScreenInfo();
    }

    private void getScreenInfo() {
        new SendGetRequest("rest/api/workflow/screen_resolution_info?workID="
                + workID + "&locale=" + MyApplication.getLang(), 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;
                }
                try {
                    ScreenInfo info = RestClient.getGson().fromJson(result, ScreenInfo.class);
                    setActionBarTitle(info.name);
                    initTitle(info.label);
                    initMessage(info.message);
                    initButtons(info.buttons);
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }

            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }
        }.execute();
    }

    /**
     * Сообщение
     *
     * @param label соообщение сообщения (wtf?)
     */
    private void initTitle(String label) {
        TextView lbl = (TextView) findViewById(R.id.action_resolution_title);
        lbl.setTypeface(Fonts.getMedium(activity));
        lbl.setText(label);
    }

    /**
     * Заголовок
     *
     * @param message сообщение заголовка
     */
    private void initMessage(String message) {
        TextView msg = (TextView) findViewById(R.id.action_resolution_message);
        msg.setTypeface(Fonts.getRoman(activity));
        msg.setText(message);
    }

    /**
     * Инициализация кнопок
     *
     * @param buttons список кнопок
     */
    private void initButtons(WorkActionsItem[] buttons) {
        LinearLayout buttonsLayout = (LinearLayout) findViewById(R.id.action_resolution_buttons);
        if (buttons != null) {
            for (WorkActionsItem button : buttons) {
                buttonsLayout.addView(getButton(button));
            }
        }
        buttonsLayout.setVisibility(View.VISIBLE);
    }

    /**
     * Метод возвращает кнопку (view) из объекта ItemWorkActions
     *
     * @param button объект класса button - описание кнопки
     * @return готовая окрашенная кнопка с лейблом
     */
    private Button getButton(WorkActionsItem button) {
        AButton action = new AButton(activity);
        action.setText(button.getLabel());
        action.setTag(button.getAction());
        action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getTag().equals(ActivityConst.RESOLUTION)) {
                    ActionUtils.checkSizeResolution(person, workID, null, activity, progressBar);
                } else {
                    finishWork();
                }
            }
        });
        if (button.getColor().equals(ActivityConst.PREFERRED)) {
            action.setBackground(AButton.GREEN);
        } else {
            action.setBackground(AButton.GRAY);
        }
        return action;
    }

    /**
     * Заголовок экрана
     *
     * @param title заголовок
     */
    private void setActionBarTitle(String title) {
        TextView actionBarTitle = (TextView) findViewById(R.id.action_resolution_title_action_bar);
        actionBarTitle.setTypeface(Fonts.getMedium(activity));
        actionBarTitle.setText(title);
    }

    /**
     * Метод используется для завершения работы статусом
     */
    private void finishWork() {
        new SendGetRequest("rest/api/workflow/work/set_state?workID=" + workID +
                "&stateID=" + 1 + "&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_change_progress), AppMsg.STYLE_ALERT).show();
                    return;
                }
                ErrorCode errorCode;
                try {
                    errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                } catch (JsonSyntaxException exc) {
                    errorCode = null;
                }
                if (errorCode != null) {
                    if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                        Intent intent = new Intent();
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    } else {
                        AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                    }
                }
                progressBar.setVisibility(View.GONE);
                super.onPostExecute(result);
            }
        }.execute();
    }

    class ScreenInfo {
        String name;
        String label;
        String message;
        WorkActionsItem[] buttons;
    }
}
