package kz.arta.synergy.workflow.mobile.android.documents.common.fragments;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.activities.MainActivity;
import kz.arta.synergy.workflow.mobile.android.common.activities.SettingsActivity;
import kz.arta.synergy.workflow.mobile.android.common.components.CustomImageView;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.offline.SyncMain;
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.Const;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.Logger;
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.common.utils.Wrapper;
import kz.arta.synergy.workflow.mobile.android.documents.DocumentConst;
import kz.arta.synergy.workflow.mobile.android.documents.common.models.FiltersDocumentItem;
import kz.arta.synergy.workflow.mobile.android.documents.offline.DocumentFiltersTable;

/**
 * Created by neox on 01.11.14.
 * Список фильтров для документов
 */
public class FragmentFiltersDocuments extends Fragment {

    private ProgressBar progressBar;
    private TextView syncButtonTitle;
    private SharedPreferences settings;
    private Person person;
    private View view;
    private ProgressWheel filtersProgressBar;
    private SwipeRefreshLayout filtersScroll;
    private Animation startAnim;
    private ListItem selectedFilterItem;
    private FragmentDocuments fragmentDocuments;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        settings = getActivity().getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);
        view = inflater.inflate(R.layout.fragment_filters, null);
        filtersProgressBar = (ProgressWheel) view.findViewById(R.id.filters_progress_bar);
        person = (Person) getArguments().getSerializable(ActivityConst.PERSON);
        startAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.start_animation_activity);
        initFilters();
        initSyncButton();
//        saveState();
        return view;
    }

    @Override
    public void onResume() {
        initSyncButton();
        super.onResume();
    }

    /**
     * Запоминаем свернуто ли приложение кнопкой "Back"
     */
    private void saveState() {
        if (settings.getBoolean(Const.BACK_PRESSED_SYNC, false)) {
            allSync(true);
        }
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(Const.BACK_PRESSED_SYNC, true);
        editor.apply();
    }

    /**
     * Инициализация кнопки синхронизации
     */
    private void initSyncButton() {

        // заголовок прогрессбара
        syncButtonTitle = (TextView) view.findViewById(R.id.sync_button_title);
        syncButtonTitle.setTypeface(Fonts.getThin(getActivity()));

        // если есть сохраненный период синхронизации - выставляем
        if (settings.contains(Const.SYNC_DATA)) {
            syncButtonTitle.setText("Последняя синхронизация: " + settings.getString(Const.SYNC_DATA, ""));
        } else {
            syncButtonTitle.setText("Синхронизация не производилась");
        }

        // иконка синхронизации
        ImageView syncIcon = (ImageView) view.findViewById(R.id.sync_icon);

        // прогрессбар
        progressBar = (ProgressBar) view.findViewById(R.id.sync_button);
        progressBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // если есть интеннет - запускаем синхронизацию
                allSync(false);
            }
        });

        // если в настройках выставлена галочка синхронизировать и если текущий пользователь запомнил себя
        if (Utils.checkSyncEnables(settings)) {
            progressBar.setVisibility(View.VISIBLE);
            syncIcon.setVisibility(View.VISIBLE);
            syncButtonTitle.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
            syncIcon.setVisibility(View.GONE);
            syncButtonTitle.setVisibility(View.GONE);
        }
    }


    /**
     * Метод выполняет полную синхронизацию. Вызывается при клике на кнопку "Синхронизация"
     *
     * @param send - нужно ли отправлять данные
     */
    private void allSync(final boolean send) {
        if (Utils.isOnline(getActivity(), person.getHost()) && Utils.checkSyncEnables(settings)) {
            if (SyncMain.canSync) {
                new SendGetRequest("about", person) {
                    @Override
                    protected void onPostExecute(String result) {
                        if (result == null) {
                            return;
                        }
                        SyncMain sync = new SyncMain(getActivity().getBaseContext());
                        sync.setPerson(person);
                        sync.setProgressBar(progressBar);
                        sync.setProgressBarTitle(syncButtonTitle);
                        sync.init();
                        sync.setShowProgress(true);
                        sync.setAllSync(true);
                        sync.setSend(send);
                        sync.clearTables(false);
                        sync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        super.onPostExecute(result);
                    }
                }.execute();
            } else {
                AppMsg.makeText(getActivity(), getString(R.string.can_not_sync), AppMsg.STYLE_ALERT).show();
            }
        }
    }

    /**
     * Инициализация кнопки "Настройки" и фильтров
     */
    private void initFilters() {
        // кнопка "Настройка"
        CustomImageView settings = (CustomImageView) view.findViewById(R.id.icon_settings);
        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SettingsActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                startActivity(intent);
            }
        });
        // главный контейнер фильтров
        filtersScroll = (SwipeRefreshLayout) view.findViewById(R.id.refresh_filters);
        filtersScroll.setColorSchemeResources(R.color.color1_update_list, R.color.color2_update_list,
                R.color.color3_update_list, R.color.color4_update_list);
        filtersScroll.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                filtersScroll.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getFilters(true);
                    }
                }, 0);
            }
        });
        getFilters(false);
    }

    /**
     * Метод загружает фильтры
     *
     * @param update обновляет ли пользователь список свайпом или нет
     */
    private void getFilters(final boolean update) {
        // все пустое пространство заливаем синим цветом
        final LinearLayout filtersLayout = (LinearLayout) view.findViewById(R.id.filters_list);
        final TextView navigatorTitle = (TextView) view.findViewById(R.id.title_action_bar_filters);
        navigatorTitle.setTypeface(Fonts.getMedium(getActivity()));
        new SendGetRequest("rest/api/docflow/doc/documents_filters?locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                filtersLayout.removeAllViews();
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                filtersProgressBar.setVisibility(View.GONE);
                filtersScroll.setRefreshing(false);
                if (result == null) {
                    filtersLayout.removeAllViews();
                    fragmentDocuments.hideProgressBar();
                    result = new DocumentFiltersTable(getActivity().getBaseContext()).get(person.getHost() + "rest/api/docflow/doc/documents_filters?locale=" + MyApplication.getLang());
                    Logger.v("RESULT = " + result);
//                    AppMsg.makeText(getActivity(), getString(R.string.no_connection), AppMsg.STYLE_ALERT).show();
//                    return;
                }
                try {
                    FiltersDocumentItem[] filters = RestClient.getGson().fromJson(result, FiltersDocumentItem[].class);
                    for (int i = 0; i < filters.length; i++) {
                        ListItem listItem = new ListItem(filters[i].getName() +
                                (!filters[i].getCount().equals(Wrapper.NO_ERROR) ? " (" + filters[i].getCount() + ")" : ""), true);
                        listItem.filterType = filters[i].getFilterType();
                        listItem.levelFilter = 1;
                        if (filters[i].getHasChildren().equals("false")) {
                            listItem.icon.setVisibility(View.INVISIBLE);
                        }
                        if (i == 0) {
                            listItem.filterName.setTextColor(getResources().getColor(R.color.selected_filter_item));
                            selectedFilterItem = listItem;
                        }
                        filtersLayout.addView(listItem);
                        filtersLayout.startAnimation(startAnim);
                    }
                    // при первом запуске отправляем интент на загрузку документов
                    if (!update) {
                        String url = "rest/api/docflow/doc/documents?filterType=" +
                                filters[0].getFilterType() + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                        if (filters[0].getFilterType().equals(DocumentConst.ALL_USER_DOCUMENTS)) {
                            fragmentDocuments.updateList(url, filters[0].getFilterType(), DocumentConst.ALL);
                        } else {
                            fragmentDocuments.updateList(url, filters[0].getFilterType(), DocumentConst.JOURNAL);
                        }
                    }
                } catch (Exception exc) {
                    filtersLayout.removeAllViews();
                    fragmentDocuments.hideProgressBar();
                    AppMsg.makeText(getActivity(), getString(R.string.no_connection), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    public void setFragmentDocuments(FragmentDocuments fragmentDocuments) {
        this.fragmentDocuments = fragmentDocuments;
    }

    /**
     * Класс отвечает за логику отображения фильтров
     */
    class ListItem extends LinearLayout {

        /**
         * Имя фильтра
         */
        TextView filterName;

        /**
         * Иконка справа от имени
         */
        ImageView icon;

        /**
         * Отступ (чем дальше уровень вложенности - тем больше отступ)
         */
        String space = "";

        /**
         * Уровень текущего фильтра
         */
        int levelFilter;

        /**
         * Тип фильтра
         */
        String filterType;

        /**
         * uuid фильтра
         */
        String filterID;

        /**
         * uuid объекта фильтра
         */
        String objectID;

        /**
         * Состояние (раскрыто/свернуто)
         */
        boolean state = false;

        public ListItem(String text, boolean bold) {

            super(getActivity());

            setOrientation(LinearLayout.VERTICAL);
            setLayoutParams(new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
            setBackgroundColor(getResources().getColor(R.color.background_color_filters));

            LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            RelativeLayout contentLayout = (RelativeLayout) layoutInflater.inflate(R.layout.filters_item, null);
            contentLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (selectedFilterItem != null) {
                        selectedFilterItem.filterName.setTextColor(Color.LTGRAY);
                    }
                    selectedFilterItem = ListItem.this;
                    filterName.setTextColor(getResources().getColor(R.color.selected_filter_item));

                    ((MainActivity) getActivity()).getFiltersSlidingMenu().toggle();
                    String url = null;
                    if (levelFilter == 1) {
                        url = "rest/api/docflow/doc/documents?filterType=" +
                                filterType + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                    } else if (levelFilter == 2) {
                        if (objectID != null) {
                            url = "rest/api/docflow/doc/documents?filterType=" +
                                    filterType + "&objectID=" + objectID + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                        } else if (filterID != null) {
                            url = "rest/api/docflow/doc/documents?filterType=" +
                                    filterType + "&filterID=" + filterID + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                        } else {
                            url = "rest/api/docflow/doc/documents?filterType=" +
                                    filterType + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                        }
                    } else if (levelFilter == 3) {
                        if (filterID != null) {
                            url = "rest/api/docflow/doc/documents?filterType=" +
                                    filterType + "&objectID=" + objectID + "&filterID=" + filterID + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                        }
                    } else if (levelFilter > 3) {
                        url = "rest/api/docflow/doc/documents?filterType=" +
                                filterType + "&objectID=" + objectID + "&filterID=" + filterID + "&pageNumber=0" + "&locale=" + MyApplication.getLang();
                    }
                    if (filterType.equals(DocumentConst.ALL_USER_DOCUMENTS) || filterType.equals(DocumentConst.USER_OWN_DOCUMENTS) ||
                            filterType.equals(DocumentConst.USER_RECEIVED_DOCUMENTS) || filterType.equals(DocumentConst.USER_SENT_DOCUMENTS)) {
                        fragmentDocuments.updateList(url, filterType, DocumentConst.ALL);
                    } else {
                        fragmentDocuments.updateList(url, filterType, DocumentConst.JOURNAL);
                    }
                }
            });

            // текст фильтра
            filterName = (TextView) contentLayout.findViewById(R.id.name_filter);
            filterName.setText(text);

            // иконка справа от текста фильтра
            icon = (ImageView) contentLayout.findViewById(R.id.icon_filter);
            icon.setOnClickListener(new ItemClickListener());

            // если находимся на первом уровне - отображаем фильтры с жирным шрифтом, иначе - обычный
            if (bold) {
                filterName.setTypeface(Fonts.getMedium(getActivity()));
            } else {
                filterName.setTypeface(Fonts.getRoman(getActivity()));
            }

            space = space + "   ";
            filterName.setTextColor(getResources().getColor(R.color.not_selected_filter_item));
            addView(contentLayout);
        }

        public void hideFilters() {
            for (int i = getChildCount() - 1; i >= 1; i--) {
                removeViewAt(i);
            }
            state = false;
            icon.setImageResource(R.drawable.filters_undetailed);
        }

        private class ItemClickListener implements OnClickListener {
            public void onClick(View view) {
                if (state) {
                    hideFilters();
                } else {
                    String url = null;
                    if (levelFilter == 1) {
                        url = "rest/api/docflow/doc/documents_filters?filterType=" +
                                filterType + "&locale=" + MyApplication.getLang();
                    } else if (levelFilter == 2) {
                        if (objectID != null) {
                            url = "rest/api/docflow/doc/documents_filters?filterType=" +
                                    filterType + "&objectID=" + objectID + "&locale=" + MyApplication.getLang();
                        } else if (filterID != null) {
                            url = "rest/api/docflow/doc/documents_filters?filterType=" +
                                    filterType + "&filterID=" + filterID + "&locale=" + MyApplication.getLang();
                        } else {
                            url = "rest/api/docflow/doc/documents_filters?filterType=" +
                                    filterType + "&locale=" + MyApplication.getLang();
                        }
                    } else if (levelFilter == 3) {
                        if (filterID != null) {
                            url = "rest/api/docflow/doc/documents_filters?filterType=" +
                                    filterType + "&objectID=" + objectID + "&filterID=" + filterID + "&locale=" + MyApplication.getLang();
                        }
                    } else if (levelFilter > 3) {
                        url = "rest/api/docflow/doc/documents_filters?filterType=" +
                                filterType + "&objectID=" + objectID + "&filterID=" + filterID + "&locale=" + MyApplication.getLang();
                    }

                    final String finalUrl = url;
                    new SendGetRequest(finalUrl, person) {
                        @Override
                        protected void onPreExecute() {
                            filtersProgressBar.setVisibility(View.VISIBLE);
                            super.onPreExecute();
                        }

                        @Override
                        protected void onPostExecute(String result) {
                            filtersScroll.setRefreshing(false);
                            filtersProgressBar.setVisibility(View.GONE);
                            if (result == null) {
                                result = new DocumentFiltersTable(getContext()).get(person.getHost() + finalUrl);
//                                AppMsg.makeText(getActivity(), getString(R.string.error_download_filters), AppMsg.STYLE_ALERT).show();
//                                return;
                            }
                            FiltersDocumentItem[] filters = null;
                            try {
                                filters = RestClient.getGson().fromJson(result, FiltersDocumentItem[].class);
                            } catch (JsonSyntaxException exc) {
                                AppMsg.makeText(getActivity(), getString(R.string.error_parsing), AppMsg.STYLE_ALERT).show();
                            }
                            if (filters == null) {
                                return;
                            }
                            for (FiltersDocumentItem filter : filters) {
                                ListItem item = new ListItem(space + filter.getName() +
                                        (!filter.getCount().equals(Wrapper.NO_ERROR) ? " (" + filter.getCount() + ")" : ""), false);
                                item.filterType = filter.getFilterType();
                                item.levelFilter = levelFilter + 1;
                                item.space = space + "    ";
                                if (filter.getFilterID() != null) {
                                    item.filterID = filter.getFilterID();
                                }
                                if (filter.getObjectID() != null) {
                                    item.objectID = filter.getObjectID();
                                }
                                if (filter.getHasChildren().equals("false")) {
                                    item.icon.setVisibility(View.INVISIBLE);
                                }
                                addView(item);
                            }
                            super.onPostExecute(result);
                        }
                    }.execute();

                    state = true;
                    icon.setImageResource(R.drawable.filters_detailed);
                }
            }
        }
    }
}
