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

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

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

import java.util.ArrayList;
import java.util.Collections;
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.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddCompletionComment;
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.Fonts;
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.works.adapters.AdapterCompletionWorkComment;
import kz.arta.synergy.workflow.mobile.android.works.manager.completion.CompletionWorkComment;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionResultItem;
import kz.arta.synergy.workflow.mobile.android.works.models.ResultWorkItem;

/**
 * Created by neox on 19.04.14.
 * Завершение работы с формой завершения комментарий
 */
public class CompletionWorkCommentActivity extends Activity {

    /**
     * Текст комментария
     */
    public static final String COMMENT = "COMMENT";

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

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

    /**
     * Настройки
     */
    private SharedPreferences settings;

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

    /**
     * Список результатов перепорученных работ
     */
    private List<ResultWorkItem> reassignedList;

    /**
     * Выбран ли результат дочерней работы либо введен свой комментарий
     */
    private boolean choose = false;

    /**
     * Номер выделенного пункта
     */
    private int selectedItem;

    /**
     * Комментарий
     */
    private EditText commentText;

    /**
     * UUID работы
     */
    private String workID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

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

        settings = activity.getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);

        person = (Person) getIntent().getSerializableExtra(ActivityConst.PERSON);
        workID = getIntent().getStringExtra(ActivityConst.WORK_ID);
        final String name = getIntent().getStringExtra(ActivityConst.WORK_NAME);

        commentText = (EditText) findViewById(R.id.end_work_comment_text);
        commentText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                choose = false;
            }
        });

        final Button save = (Button) findViewById(R.id.end_work_comment_button_save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = commentText.getText().toString();
                if (text.trim().length() != 0 && text.length() != 0) {
                    if (Utils.isOnline(activity, person.getHost())) {
                        progressBar.setVisibility(View.VISIBLE);
                        CompletionWorkComment completionWorkComment = new CompletionWorkComment();
                        completionWorkComment.setPerson(person);
                        completionWorkComment.setActivity(activity);
                        completionWorkComment.setWorkID(workID);
                        completionWorkComment.setProgressBar(progressBar);
                        if (choose) {
                            completionWorkComment.setChoose(true);
                            completionWorkComment.setResultID(reassignedList.get(selectedItem).getResultID());
                        } else {
                            completionWorkComment.setTextComment(text);
                        }
                        completionWorkComment.execute();
                    } else if (Utils.checkSyncEnables(settings)) {
                        new AddCompletionComment(activity).add(workID, text, name);
                        Intent intent = new Intent();
                        intent.putExtra(COMMENT, text);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                } else {
                    if (choose) {
                        AppMsg.makeText(activity, getString(R.string.enter_comment_or_choose_reassigned), AppMsg.STYLE_ALERT).show();
                    } else {
                        AppMsg.makeText(activity, getString(R.string.enter_comment), AppMsg.STYLE_ALERT).show();
                    }
                }
            }
        });

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

        new GetResults().execute();
    }

    /**
     * Инициализаця компонентов по умолчанию
     */
    private void initDefaultComponents() {
        ((TextView) findViewById(R.id.end_work_comment_text_view)).setText(getString(R.string.enter_comment));
        (findViewById(R.id.end_work_comment_no_child)).setVisibility(View.VISIBLE);
    }

    /**
     * Инициализация компонентов, если есть завершенные результаты дочерних работ
     */
    private void initComponentsPreviousResult() {
        reassignedList = new ArrayList<>();
        ((TextView) findViewById(R.id.end_work_title_or_choose)).setText(getString(R.string.choose_reassigned));
        (findViewById(R.id.end_work_comment_have_child)).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.end_work_comment_text_view)).setText(getString(R.string.or_enter_comment));
        (findViewById(R.id.end_work_comment_no_child)).setVisibility(View.VISIBLE);
    }

    /**
     * Инициализация списка дочерних результатов
     *
     * @param items пункты
     */
    private void initList(final ResultWorkItem[] items) {
        ListView reassigned = (ListView) findViewById(R.id.end_work_comment_list);
        AdapterCompletionWorkComment adapterCompletionWorkComment = new AdapterCompletionWorkComment(activity, reassignedList);
        reassigned.setAdapter(adapterCompletionWorkComment);
        Collections.addAll(reassignedList, items);
        adapterCompletionWorkComment.notifyDataSetChanged();
        reassigned.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                choose = true;
                selectedItem = i;
                commentText.setText(items[i].getComment());
            }
        });
    }

    /**
     * Получение завершенные результаты дочерних работ
     */
    class GetResults extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPostExecute(String result) {
            progressBar.setVisibility(View.GONE);
            if (result != null) {
                try {
                    CompletionResultItem res = RestClient.getGson().fromJson(result, CompletionResultItem.class);
                    if (res.getPrevious_results().length != 0) {
                        initComponentsPreviousResult();
                        initList(res.getPrevious_results());
                    } else {
                        initDefaultComponents();
                    }
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                }
            } else if (Utils.checkSyncEnables(settings)) {
                initDefaultComponents();
            } else {
                AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
            }
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/get_completion_data?workID=" +
                    workID + "&locale=" + MyApplication.getLang());
        }
    }
}
