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

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.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.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
import kz.arta.synergy.workflow.mobile.android.users.activities.UserChooserActivity;
import kz.arta.synergy.workflow.mobile.android.works.manager.send.TransmitWork;

/**
 * Created by neox on 07.05.14.
 * Передача работы другому пользователю
 */
public class TransmitWorkActivity extends Activity {

    private static final int USER_CHOOSER = 1;

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

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

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

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

    /**
     * Имя пользователя кому передается работа
     */
    private TextView userName;

    /**
     * uuid пользователя кому передается работа
     */
    private String userID;

    /**
     * uuid раоты
     */
    private String workID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
            TextView actionBarTitle = (TextView) findViewById(R.id.title_action_bar_transmit);
            actionBarTitle.setTypeface(Fonts.getMedium(activity));
            actionBarTitle.setText(getString(R.string.send));
        }

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

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

        initComponents();

        new GetParams().execute();
    }

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

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

        userName = (TextView) findViewById(R.id.transmit_work_user);
        userName.setTypeface(Fonts.getMedium(activity));
        userName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(TransmitWorkActivity.this, UserChooserActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.SHOW_ALL, "true");
                intent.putExtra(ActivityConst.USER_ID, userID);
                intent.putExtra(ActivityConst.USER_NAME, userName.getText());
                startActivityForResult(intent, USER_CHOOSER);

            }
        });

        Button button = (Button) findViewById(R.id.transmit_work_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (workName.getText().length() != 0 && userName.getText().length() != 0) {
                    TransmitWork transmitWork = new TransmitWork();
                    transmitWork.setActivity(activity);
                    transmitWork.setPerson(person);
                    transmitWork.setWorkID(workID);
                    transmitWork.setUserID(userID);
                    transmitWork.setName(workName.getText().toString());
                    transmitWork.setProgressBar(progressBar);
                    transmitWork.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 == USER_CHOOSER && resultCode != RESULT_CANCELED) {
            String userName = data.getStringExtra(ActivityConst.USER_NAME);
            userID = data.getStringExtra(ActivityConst.USER_ID);
            this.userName.setText(userName);
        }
    }

    @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 params;
            try {
                params = RestClient.getGson().fromJson(result, ScreenInfo.class);
                workName.setText(params.name);
            } 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) {
            return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/send_work_info?workID="
                    + workID + "&actionType=TRANSMIT&locale=" + MyApplication.getLang());
        }
    }

    class ScreenInfo {

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