package kz.arta.synergy.workflow.mobile.android.forms.general.components.addressbook;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

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

import java.net.URLEncoder;
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.components.SearchEditText;
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;

/**
 * Created by neox on 30.05.16.
 * Адресная книга
 */
public class AddressBookActivity extends Activity {

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

    /**
     * Текущий тип
     */
    private int itemType = AddressBookConst.PERSON;

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

    /**
     * Данные в списке
     */
    private List<AddressBookModel> data;

    /**
     * Адаптер списка
     */
    private AddressBookAdapter adapter;

    /**
     * Номер страницы
     */
    private int pageNumber = 0;

    /**
     * Загружается ли список в данный момент
     */
    private boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

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

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

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

        final SearchEditText searchEditText = (SearchEditText) findViewById(R.id.address_book_search_edit_text);
        searchEditText.setListener(new SearchEditText.SearchTextListener() {
            @Override
            public void onTextChanged(String searchString) {
                getList(searchString, true);
            }
        });

        final TextView actionBarTitle = (TextView) findViewById(R.id.address_book_activity_action_bar_title);
        actionBarTitle.setText(getString(R.string.peoples));
        actionBarTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] itemsArray = {getString(R.string.peoples), getString(R.string.organizations)};
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddressBookActivity.this);
                alertDialog.setItems(itemsArray, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        searchEditText.clear();
                        pageNumber = 0;
                        actionBarTitle.setText(itemsArray[which]);
                        itemType = which;
                        getList("", true);
                    }
                });
                alertDialog.setCancelable(true);
                alertDialog.show();
            }
        });

        data = new ArrayList<>();

        adapter = new AddressBookAdapter(AddressBookActivity.this, data);

        ListView listView = (ListView) findViewById(R.id.address_book_list);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (totalItemCount >= AddressBookConst.COUNT_IN_PART) {
                    final int lastItem = firstVisibleItem + visibleItemCount;
                    if (lastItem == totalItemCount && !isLoading) {
                        isLoading = true;
                        pageNumber += 1;
                        getList("", false);
                    }
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setSelected(false);
                }
                data.get(position).setSelected(true);
                adapter.notifyDataSetChanged();
            }
        });

        listView.setAdapter(adapter);

        // кнопка "Сохранить"
        Button save = (Button) findViewById(R.id.address_book_button_save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddressBookModel selectedItem = getSelectedItem();
                if (selectedItem == null) {
                    AppMsg.makeText(AddressBookActivity.this, getString(R.string.element_not_selected), AppMsg.STYLE_ALERT).show();
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra(ActivityConst.SELECTED, selectedItem);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        getList("", true);
    }

    /**
     * Метод возвращает выделенный элемент в списке
     *
     * @return выделенный элемент
     */
    private AddressBookModel getSelectedItem() {
        for (AddressBookModel item : data) {
            if (item.isSelected()) {
                return item;
            }
        }
        return null;
    }

    private void getList(String search, final boolean clear) {
        try {
            search = URLEncoder.encode(search, "utf-8");
        } catch (Exception ignored) {
        }
        new SendGetRequest("rest/api/addressbook/items?recordsCount=30&itemType=" + itemType + "&search=" + search + "&page=" + pageNumber, person) {
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                progressBar.setVisibility(View.GONE);
                if (result == null) {
                    return;
                }
                try {
                    if (clear) {
                        data.clear();
                    }
                    AddressBookList addressBookList = RestClient.getGson().fromJson(result, AddressBookList.class);
                    Collections.addAll(data, addressBookList.array);
                    adapter.notifyDataSetChanged();
                    isLoading = addressBookList.array.length == 0;
                } catch (Exception exc) {
                    // handling error ...
                }
            }
        }.execute();
    }

    private class AddressBookList {
        AddressBookModel[] array;
    }
}
