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

import android.app.ActionBar;
import android.app.Activity;
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.ImageView;
import android.widget.ListView;

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

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
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;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.registrychooser.models.RegistryDataModel;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.registrychooser.models.RegistryInfoModel;

/**
 * Created by neox on 02.06.16.
 * Выбор записи реестра
 */
public class RegistryChooserActivity extends Activity {

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

    /**
     * Данные списка
     */
    private List<List<RegistryDataModel.Data>> data;

    /**
     * Адаптер
     */
    private RegistryChooserAdapter adapter;

    /**
     * Тип отображения плашек (true - полный вид, false - только значащее содержимое)
     */
    private boolean showAll;

    /**
     * Информация о колонках
     */
    private RegistryInfoModel regInfo;

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

    /**
     * Диалог
     */
    private RegistryChooserDialog dialog;

    /**
     * Колонка по которое производится фильтрация
     */
    private RegistryInfoModel.Columns filteredColumn;

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

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

    /**
     * Идентификатор текущего реестра
     */
    private String registryID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

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

        person = (Person) getIntent().getSerializableExtra(ActivityConst.PERSON);
        registryID = getIntent().getStringExtra(ActivityConst.REGISTRY);

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

        data = new ArrayList<>();

        final ImageView sortButton = (ImageView) findViewById(R.id.registry_activity_sort_button);
        sortButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.setShowAll(showAll);
                dialog.setColumns(regInfo.getColumns());
                dialog.showDialog();
            }
        });

        final ImageView modeButton = (ImageView) findViewById(R.id.registry_activity_change_mode_button);
        modeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (showAll) {
                    showAll = false;
                    modeButton.setImageResource(R.drawable.top_bar_list_long);
                } else {
                    showAll = true;
                    modeButton.setImageResource(R.drawable.top_bar_list_short);
                }
                adapter.setShowAll(showAll);
                adapter.notifyDataSetChanged();
            }
        });

        dialog = (RegistryChooserDialog) findViewById(R.id.registry_chooser_activity_dialog);
        dialog.addRegistryCallBack(new RegistryChooserDialog.RegistryCallBack() {
            @Override
            public void onSelect(RegistryInfoModel.Columns field) {
                filteredColumn = field;
                sortButton.setImageResource(field.isUpIcon() ? R.drawable.top_bar_sort_asc : R.drawable.top_bar_sort_desc);
                getData("", true, true);
            }
        });

        SearchEditText search = (SearchEditText) findViewById(R.id.registry_chooser_activity_search_edit_text);
        search.setListener(new SearchEditText.SearchTextListener() {
            @Override
            public void onTextChanged(String searchString) {
                getData(searchString, true, true);
            }
        });

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

        getInfo();
    }

    /**
     * Метод возвращает dataUUID для выделенной записи
     *
     * @return dataUUID
     */
    private String getSelectedDataUUID() {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).get(0).isSelected()) {
                return data.get(i).get(0).getUuid();
            }
        }
        return null;
    }

    /**
     * Инициализация списка
     */
    private void initList() {
        ListView list = (ListView) findViewById(R.id.registry_chooser_activity_list);
        adapter = new RegistryChooserAdapter(RegistryChooserActivity.this, data, showAll, regInfo);
        list.setAdapter(adapter);
        list.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 >= 30) {
                    final int lastItem = firstVisibleItem + visibleItemCount;
                    if (lastItem == totalItemCount && !isLoading) {
                        isLoading = true;
                        pageNumber += 1;
                        getData("", false, false);
                    }
                }
            }
        });
        list.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).get(0).setSelected(false);
                }
                data.get(position).get(0).setSelected(true);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * Получение описание реестра
     */
    private void getInfo() {
        new SendGetRequest("rest/api/registry/info?registryID=" + registryID, person) {
            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    progressBar.setVisibility(View.GONE);
                    AppMsg.makeText(RegistryChooserActivity.this, getString(R.string.error_to_get_registry_info), AppMsg.STYLE_ALERT).show();
                    return;
                }
                try {
                    regInfo = RestClient.getGson().fromJson(result, RegistryInfoModel.class);
                    if (regInfo != null) {
                        initList();
                        getData("", false, true);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        AppMsg.makeText(RegistryChooserActivity.this, getString(R.string.error_to_get_registry_info), AppMsg.STYLE_ALERT).show();
                    }
                } catch (Exception exc) {
                    progressBar.setVisibility(View.GONE);
                    AppMsg.makeText(RegistryChooserActivity.this, getString(R.string.error_to_get_registry_info), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    private void getData(String search, final boolean showProgressBar, final boolean clearList) {
        try {
            search = URLEncoder.encode(search, "utf-8");
        } catch (Exception ignored) {
        }
        String filtered = "";
        if (filteredColumn != null) {
            filtered = "&sortCmpID=" + filteredColumn.getColumnID() + "&sortDesc=" + !filteredColumn.isUpIcon();
        }
        new SendGetRequest("rest/api/registry/data_ext?registryID=" + registryID +
                "&pageNumber=" + pageNumber +
                "&countInPart=30" +
                "&searchString=" + search + filtered, person) {
            @Override
            protected void onPreExecute() {
                if (showProgressBar) {
                    progressBar.setVisibility(View.VISIBLE);
                }
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                if (result == null) {
                    AppMsg.makeText(RegistryChooserActivity.this, getString(R.string.error_to_get_registry_data), AppMsg.STYLE_ALERT).show();
                    return;
                }
                try {
                    if (clearList) {
                        data.clear();
                    }
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray resultArray = jsonObject.getJSONArray("result");
                    for (int i = 0; i < resultArray.length(); i++) {
                        JSONObject registryObject = resultArray.getJSONObject(i);
                        String documentID = registryObject.getString("documentID");
                        String dataUUID = registryObject.getString("dataUUID");
                        int state = registryObject.getInt("state");
                        JSONObject fieldsValue = registryObject.getJSONObject("fieldValue");
                        List<RegistryDataModel.Data> buf = new ArrayList<>();
                        if (fieldsValue != null && fieldsValue.names() != null) {
                            for (int j = 0; j < fieldsValue.names().length(); j++) {
                                String key = fieldsValue.names().getString(j);
                                String value = fieldsValue.getString(fieldsValue.names().getString(j));
                                RegistryDataModel.Data data = new RegistryDataModel.Data();
                                data.setUuid(documentID);
                                data.setCmp_id(key);
                                data.setCmp_data(value);
                                data.setDataUUID(dataUUID);
                                data.setState(state);
                                buf.add(data);
                            }
                            data.add(buf);
                        } else {
                            buf.add(new RegistryDataModel.Data());
                            data.add(buf);
                        }
                    }
                    isLoading = resultArray.length() == 0;
                    adapter.notifyDataSetChanged();
                } catch (Exception exc) {
                    AppMsg.makeText(RegistryChooserActivity.this, getString(R.string.error_to_get_registry_data), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    @Override
    public void onBackPressed() {
        if (dialog.isShowed()) {
            dialog.hideDialog();
        } else {
            super.onBackPressed();
        }
    }
}
