package kz.arta.synergy.workflow.mobile.android.works.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.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.offline.get.WorkFiltersTable;
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.FragmentConst;
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.works.models.FilterWorkItem;

/**
 * Created by neox on 01.11.14.
 * Список фильтров для работ
 */
public class FragmentFiltersWorks 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 LinearLayout layoutFilters;
    private ListItem selectedFilterItem;

    @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();
//        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 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();
                    }
                }, 0);
            }
        });
        getFilters();
    }

    /**
     * Инициализация кнопки синхронизации
     */
    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 getFilters() {

        // все пустое пространство заливаем синим цветом
        layoutFilters = (LinearLayout) view.findViewById(R.id.filters_list);
        layoutFilters.removeAllViews();

        final TextView navigatorTitle = (TextView) view.findViewById(R.id.title_action_bar_filters);
        navigatorTitle.setTypeface(Fonts.getMedium(getActivity()));

        new SendGetRequest("rest/api/workflow/works/filters/" + person.getUuid() +
                "?getCounters=true&locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPostExecute(String result) {
                filtersProgressBar.setVisibility(View.GONE);
                filtersScroll.setRefreshing(false);
                if (result != null) {
                    try {
                        FilterWorkItem[] filtersItems;
                        filtersItems = RestClient.getGson().fromJson(result, FilterWorkItem[].class);
                        if (filtersItems != null) {
                            addItemFilter(filtersItems);
                        }
                    } catch (Exception ignored) {
                    }
                } else if (Utils.checkSyncEnables(settings)) {
                    initOfflineFilters();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Оффайн фильтры
     */
    private void initOfflineFilters() {
        try {
            FilterWorkItem[] filtersItems;
            String filters = new WorkFiltersTable(getActivity()).getFilter(person.getHost() +
                    "rest/api/workflow/works/filters/" + person.getUuid() + "?getCounters=true&locale=" + MyApplication.getLang());
            if (filters != null) {
                filtersItems = RestClient.getGson().fromJson(filters, FilterWorkItem[].class);
                if (filtersItems != null) {
                    addItemFilter(filtersItems);
                }
            }
            filtersScroll.setRefreshing(false);
        } catch (Exception ignored) {
        }
    }

    /**
     * Метод добавляет пункты в список фильтров
     *
     * @param filtersItem список
     */
    private void addItemFilter(FilterWorkItem[] filtersItem) {
        for (int i = 0; i < filtersItem.length; i++) {
            ListItem listItem = new ListItem(getFilterName(filtersItem[i]));
            listItem.filterType = filtersItem[i].getFilterType();
            listItem.levelFilter = 1;
            if (filtersItem[i].getHasChildren().equals("false")) {
                listItem.filterIcon.setVisibility(View.INVISIBLE);
            }
            if (i == 0) {
                listItem.filterName.setTextColor(getResources().getColor(R.color.selected_filter_item));
                selectedFilterItem = listItem;
            }
            layoutFilters.addView(listItem);
            layoutFilters.startAnimation(startAnim);
        }
    }

    /**
     * Метод возвращает добработанное имя счетчика
     *
     * @param filtersItem - пункт фильтра
     * @return - распарсернную строку
     */
    private String getFilterName(FilterWorkItem filtersItem) {
        StringBuilder filterName = new StringBuilder(filtersItem.getName());
        if (filtersItem.getCounters() != null) {
            if (filtersItem.getCounters().getTotal().equals(Wrapper.NO_ERROR)) {
                return filtersItem.getName();
            }
            if (!filtersItem.getCounters().getIs_new().equals(Wrapper.NO_ERROR) && !filtersItem.getFilterType().equals("ON_CONTROL")) {
                filterName.append(" (");
                filterName.append(filtersItem.getCounters().getIs_new());
                filterName.append("/");
                filterName.append(filtersItem.getCounters().getTotal());
                filterName.append(")");
            } else {
                filterName.append(" (");
                filterName.append(filtersItem.getCounters().getTotal());
                filterName.append(")");
            }
        }
        return filterName.toString();
    }

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

        TextView filterName;
        ImageView filterIcon;

        String filterType;
        String filterID;
        String objectID;
        String type;

        String text;
        String space = "    ";

        int level = 1;
        int levelFilter;
        boolean state = false;

        public ListItem(String text) {
            this(text, 1);
        }

        public ListItem(String text, int level) {

            super(getActivity());

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

            LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final 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;

                    if (levelFilter == 1) {

                        url = "rest/api/workflow/works/list/" + person.getUuid() + "?filterType=" + filterType +
                                "&startRecord=0&recordsCount=" + FragmentConst.DEFAULT_COUNT_WORKS + "&locale=" + MyApplication.getLang();

                    } else {

                        url = "rest/api/workflow/works/list/" + person.getUuid() + "?filterType=" + filterType +
                                "&startRecord=0&recordsCount=" + FragmentConst.DEFAULT_COUNT_WORKS + "&locale=" + MyApplication.getLang();

                        if (filterID != null && !filterID.isEmpty()) {
                            url = url + "&filterID=" + filterID;
                        }

                        if (objectID != null && !objectID.isEmpty()) {
                            url = url + "&objectID=" + objectID;
                        }

                    }

                    // отправляем сообщение широковещательному приемнику
                    Intent intent = new Intent(FragmentConst.UPDATE_LIST_BY_FILTERS);
                    intent.putExtra(FragmentConst.URL_TO_WORKS, url);
                    intent.putExtra(DocumentConst.FILTER_TYPE, filterType);
                    intent.putExtra(DocumentConst.FILTER_ID, filterID);
                    intent.putExtra(DocumentConst.OBJECT_ID, objectID);
                    getActivity().sendBroadcast(intent);

                }
            });

            filterName = (TextView) contentLayout.findViewById(R.id.name_filter);
            filterName.setText(text);

            filterIcon = (ImageView) contentLayout.findViewById(R.id.icon_filter);
            filterIcon.setOnClickListener(new ItemClickListener());

            if (level == 1) {
                filterName.setTypeface(Fonts.getMedium(getActivity()));
            } else {
                filterName.setTypeface(Fonts.getRoman(getActivity()));
            }
            this.text = text;
            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;
            filterIcon.setImageResource(R.drawable.filters_undetailed);
        }

        private class ItemClickListener implements OnClickListener {

            public void onClick(View view) {

                if (state) {
                    hideFilters();
                } else {

                    filtersProgressBar.setVisibility(View.VISIBLE);

                    if (levelFilter == 1) {

                        final String url = "rest/api/workflow/works/filters/" + person.getUuid() +
                                "?filterType=" + filterType + "&getCounters=true&locale=" + MyApplication.getLang();

                        new SendGetRequest(url, person) {

                            protected void onPostExecute(String result) {

                                filtersProgressBar.setVisibility(View.GONE);

                                FilterWorkItem[] filtersItem;
                                String filters;

                                if (result != null) {
                                    filters = result;
                                } else if (Utils.checkSyncEnables(settings)) {
                                    filters = new WorkFiltersTable(getActivity()).getFilter(person.getHost() + url);
                                    Logger.v("filters = " + person.getHost() + url);
                                    Logger.v("filters url = " + filters);
                                } else {
                                    AppMsg.makeText(getActivity(), getString(R.string.error_download_filters), AppMsg.STYLE_ALERT).show();
                                    return;
                                }

                                if (filters == null) {
                                    return;
                                }

                                filtersItem = RestClient.getGson().fromJson(filters, FilterWorkItem[].class);
                                if (filtersItem == null || filtersItem.length == 0) {
                                    return;
                                }

                                for (FilterWorkItem filterItem : filtersItem) {

                                    ListItem item = new ListItem("   " + getFilterName(filterItem), level + 1);

                                    item.levelFilter = 2;

                                    if (filterItem.getFilterType() != null && !filterItem.getFilterType().isEmpty()) {
                                        item.filterType = filterItem.getFilterType();
                                    }

                                    if (filterItem.getFilterID() != null && !filterItem.getFilterID().isEmpty()) {
                                        item.filterID = filterItem.getFilterID();
                                    }

                                    if (filterItem.getObjectID() != null && !filterItem.getObjectID().isEmpty()) {
                                        item.objectID = filterItem.getObjectID();
                                    }

                                    if (filterItem.getHasChildren().equals("false")) {
                                        item.filterIcon.setVisibility(View.INVISIBLE);
                                    }

                                    addView(item);
                                }
                            }
                        }.execute();

                    } else if (levelFilter >= 2) {

                        String url = "rest/api/workflow/works/filters/" + person.getUuid() +
                                "?filterType=" + filterType + "&getCounters=true&locale=" + MyApplication.getLang();

                        if (filterID != null && !filterID.isEmpty()) {
                            url = url + "&parentID=" + filterID;
                        }

                        if (objectID != null && !objectID.isEmpty()) {
                            url = url + "&parentObjectID=" + objectID;
                        }

                        final String finalUrl = url;

                        new SendGetRequest(finalUrl, person) {

                            protected void onPostExecute(String result) {

                                filtersProgressBar.setVisibility(View.GONE);

                                FilterWorkItem[] filtersItem;
                                String filters;

                                if (result != null) {
                                    filters = result;
                                } else if (Utils.checkSyncEnables(settings)) {
                                    filters = new WorkFiltersTable(getActivity()).getFilter(person.getHost() + finalUrl);
                                    Logger.v("filters url = " + filters);
                                } else {
                                    AppMsg.makeText(getActivity(), getString(R.string.error_download_filters), AppMsg.STYLE_ALERT);
                                    return;
                                }

                                if (filters == null) {
                                    return;
                                }

                                filtersItem = RestClient.getGson().fromJson(filters, FilterWorkItem[].class);

                                if (filtersItem == null || filtersItem.length == 0) {
                                    return;
                                }

                                for (FilterWorkItem filterItem : filtersItem) {

                                    ListItem item = new ListItem(space + getFilterName(filterItem), level + 1);

                                    item.levelFilter = 3;
                                    item.space = space + "   ";

                                    if (filterItem.getFilterType() != null && !filterItem.getFilterType().isEmpty()) {
                                        item.filterType = filterItem.getFilterType();
                                    }

                                    if (filterItem.getFilterID() != null && !filterItem.getFilterID().isEmpty()) {
                                        item.filterID = filterItem.getFilterID();
                                    }

                                    if (filterItem.getObjectID() != null && !filterItem.getObjectID().isEmpty()) {
                                        item.objectID = filterItem.getObjectID();
                                    }

                                    if (filterItem.getHasChildren().equals("false")) {
                                        item.filterIcon.setVisibility(View.INVISIBLE);
                                    }

                                    addView(item);
                                }
                            }
                        }.execute();
                    }
                    state = true;
                    filterIcon.setImageResource(R.drawable.filters_detailed);
                }
            }
        }
    }
}
