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

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.devspark.appmsg.AppMsg;
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.documents.route.RoutesConst;
import kz.arta.synergy.workflow.mobile.android.documents.route.adapters.AdapterRoutesList;
import kz.arta.synergy.workflow.mobile.android.documents.route.models.RouteListItem;

/**
 * Created by neox on 24.07.15.
 * Список маршрутов доступных пользователю
 */
public class RoutesListActivity extends Activity {

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

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

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

    /**
     * Выделенный маршрут
     */
    private RouteListItem route;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.route_list_activity);
        super.onCreate(savedInstanceState);

        activity = this;

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

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

        init();

        getRoutes();

    }

    /**
     * Инициализация кнопки "Сохранить"
     */
    private void init() {
        progressBar = (ProgressWheel) findViewById(R.id.route_list_activity_progress_bar);
        Button saveButton = (Button) findViewById(R.id.route_list_activity_button);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (route == null) {
                    AppMsg.makeText(activity, getString(R.string.choose_route), AppMsg.STYLE_ALERT).show();
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra(RoutesConst.ROUTE_LIST_ITEM, route);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    /**
     * Метод получает маршруты
     */
    private void getRoutes() {
        new SendGetRequest("rest/api/docflow/doc/routes", person) {
            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                if (result == null) {
                    AppMsg.makeText(activity, getString(R.string.error_to_get_route_list), AppMsg.STYLE_ALERT).show();
                    return;
                }
                try {
                    final RouteListItem[] routeItems = RestClient.getGson().fromJson(result, RouteListItem[].class);
                    final ArrayAdapter<RouteListItem> routeAdapter = new AdapterRoutesList(activity, routeItems);
                    ListView routeList = (ListView) findViewById(R.id.route_list_activity_list);
                    routeList.setAdapter(routeAdapter);
                    routeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            for (int i = 0; i < routeItems.length; i++) {
                                if (i != position) {
                                    routeItems[i].setSelected(false);
                                }
                            }
                            routeItems[position].setSelected(!routeItems[position].isSelected());
                            routeAdapter.notifyDataSetChanged();
                            if (routeItems[position].isSelected()) {
                                route = routeItems[position];
                            } else {
                                route = null;
                            }
                        }
                    });
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

}
