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

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.registrychooser.models.RegistryInfoModel;

/**
 * Created by neox on 02.06.16.
 * Диалог выбора реестра
 */
public class RegistryChooserDialog extends RelativeLayout {

    /**
     * Контекст
     */
    private Context context;

    /**
     * Отображать ли все или нет
     */
    private boolean showAll;

    /**
     * Список колонок
     */
    private List<RegistryInfoModel.Columns> columns;

    /**
     * Отображен ли диалог в данный момент
     */
    private boolean showed;
    /**
     * Callback
     */
    private RegistryCallBack registryCallBack;
    /**
     * Выбранная колонка
     */
    private RegistryInfoModel.Columns selectedColumn;

    /**
     * Конструктор
     *
     * @param context контекст
     * @param attrs   атрибуты
     */
    public RegistryChooserDialog(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    /**
     * Метод отображает диалог на экране
     */
    @SuppressLint("ResourceType")
    public void showDialog() {

        if (columns == null || columns.isEmpty()) {
            hideDialog();
            return;
        }


        showed = true;

        Resources r = getResources();

        // высота сплита
        int splitHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, r.getDisplayMetrics());
        // отступы у заголовка
        int pxTitleMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        // отступы слева/справа у диалога
        int pxLeftRight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, r.getDisplayMetrics());
        // отступы снизу/сверху у диалога
        int pxTopBottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        // фон
        LayoutParams backgroundParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        backgroundParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        backgroundParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        RelativeLayout background = new RelativeLayout(context);
        background.setLayoutParams(backgroundParams);
        background.setBackgroundColor(Color.parseColor("#000000"));
        background.setAlpha(0.7f);
        background.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDialog();
            }
        });

        addView(background);

        // диалог
        LayoutParams contentParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        contentParams.setMargins(pxLeftRight, pxTopBottom, pxLeftRight, pxTopBottom);
        contentParams.addRule(RelativeLayout.CENTER_IN_PARENT);

        RelativeLayout content = new RelativeLayout(context);
        content.setLayoutParams(contentParams);
        content.setBackgroundResource(R.drawable.registry_chooser_background);
        content.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        addView(content);

        // заголовок
        LayoutParams titleParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        titleParams.setMargins(pxTitleMargin, pxTitleMargin, pxTitleMargin, pxTitleMargin);
        titleParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        titleParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        TextView title = new TextView(context);
        title.setId(1);
        title.setLayoutParams(titleParams);
        title.setText("Сортировать по полю");
        title.setTypeface(Fonts.getMedium(context));
        title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

        content.addView(title);

        // верхний сплит
        LayoutParams headerSplitParams = new LayoutParams(LayoutParams.WRAP_CONTENT, splitHeight);
        headerSplitParams.addRule(RelativeLayout.BELOW, title.getId());

        final View headerSplit = new View(context);
        headerSplit.setId(2);
        headerSplit.setLayoutParams(headerSplitParams);
        headerSplit.setBackgroundColor(context.getResources().getColor(R.color.background_layout_stroke_color));
        headerSplit.setVisibility(View.GONE);

        content.addView(headerSplit);

        // нижняя панель с кнопками
        LayoutParams bottomPanelParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        bottomPanelParams.setMargins(pxTitleMargin, pxTitleMargin, pxTitleMargin, pxTitleMargin);
        bottomPanelParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        bottomPanelParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        LinearLayout bottomPanel = new LinearLayout(context);
        bottomPanel.setLayoutParams(bottomPanelParams);
        bottomPanel.setId(3);
        bottomPanel.setOrientation(LinearLayout.HORIZONTAL);

        LinearLayout.LayoutParams cancelParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        cancelParams.setMargins(0, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 20, r.getDisplayMetrics()), 0);

        // кнопка "Отмена"
        TextView cancel = new TextView(context);
        cancel.setLayoutParams(cancelParams);
        cancel.setText("Отмена".toUpperCase());
        cancel.setTypeface(Fonts.getMedium(context));
        cancel.setTextColor(Color.parseColor("#679eb8"));
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RegistryChooserDialog.this.hideDialog();
            }
        });

        // кнопка "Принять
        TextView accept = new TextView(context);
        accept.setText("Принять".toUpperCase());
        accept.setTypeface(Fonts.getMedium(context));
        accept.setTextColor(Color.parseColor("#679eb8"));
        accept.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDialog();
                if (selectedColumn == null) {
                    return;
                }
                if (registryCallBack != null) {
                    registryCallBack.onSelect(selectedColumn);
                }
            }
        });

        bottomPanel.addView(cancel);
        bottomPanel.addView(accept);

        content.addView(bottomPanel);

        // список
        LayoutParams listViewParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        listViewParams.addRule(RelativeLayout.BELOW, headerSplit.getId());
        listViewParams.addRule(RelativeLayout.ABOVE, bottomPanel.getId());

        final List<RegistryInfoModel.Columns> listObjects = new ArrayList<>();
        for (RegistryInfoModel.Columns column : columns) {
            column.setUpIcon(false);
            column.setShowIcon(false);
            if (!showAll) {
                if (column.getVisible().equals("1") && column.getBody().equals("1")) {
                    listObjects.add(column);
                }
            } else {
                if (column.getVisible().equals("1")) {
                    listObjects.add(column);
                }
            }
        }


        final ListAdapter adapter = new ListAdapter(context, listObjects);

        final ListView list = new ListView(context);
        list.setDivider(null);
        list.setDividerHeight(0);
        list.setId(4);
        list.setLayoutParams(listViewParams);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (listObjects.get(position).isShowIcon()) {
                    listObjects.get(position).setUpIcon(!listObjects.get(position).isUpIcon());
                    adapter.notifyDataSetChanged();
                } else {
                    for (RegistryInfoModel.Columns column : listObjects) {
                        column.setShowIcon(false);
                        column.setUpIcon(false);
                    }

                    listObjects.get(position).setShowIcon(true);
                    adapter.notifyDataSetChanged();
                }
                selectedColumn = listObjects.get(position);
            }
        });

        list.setAdapter(adapter);

        content.addView(list);

        // нижний сплит
        LayoutParams bottomSplitParams = new LayoutParams(LayoutParams.WRAP_CONTENT, splitHeight);
        bottomSplitParams.addRule(RelativeLayout.BELOW, list.getId());

        final View bottomSplit = new View(context);
        bottomSplit.setLayoutParams(bottomSplitParams);
        bottomSplit.setBackgroundColor(context.getResources().getColor(R.color.background_layout_stroke_color));
        bottomSplit.setVisibility(View.GONE);

        content.addView(bottomSplit);

        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
                if (absListView.getCount() == 0) {
                    return;
                }
                if (absListView.getChildCount() == 0 || absListView.getChildAt(0).getTop() == 0) {
                    headerSplit.setVisibility(View.GONE);
                } else {
                    headerSplit.setVisibility(View.VISIBLE);
                }
                if (absListView.getLastVisiblePosition() == absListView.getAdapter().getCount() - 1 &&
                        absListView.getChildAt(absListView.getChildCount() - 1).getBottom() <= absListView.getHeight()) {
                    bottomSplit.setVisibility(View.GONE);
                } else {
                    bottomSplit.setVisibility(View.VISIBLE);
                }
            }
        });

        RegistryChooserDialog.this.setVisibility(View.VISIBLE);
    }


    /**
     * Метод закрывает диалог
     */
    public void hideDialog() {
        RegistryChooserDialog.this.removeAllViews();
        RegistryChooserDialog.this.setVisibility(View.GONE);
        showed = false;
    }

    public void setShowAll(boolean showAll) {
        this.showAll = showAll;
    }

    public void setColumns(List<RegistryInfoModel.Columns> columns) {
        this.columns = columns;
    }

    public boolean isShowed() {
        return showed;
    }

    public void setShowed(boolean showed) {
        this.showed = showed;
    }

    public void addRegistryCallBack(RegistryCallBack registryCallBack) {
        this.registryCallBack = registryCallBack;
    }

    public interface RegistryCallBack {
        void onSelect(RegistryInfoModel.Columns field);
    }

    /**
     * Адаптер списка
     */
    private class ListAdapter extends ArrayAdapter<RegistryInfoModel.Columns> {

        private List<RegistryInfoModel.Columns> list;
        private Context context;

        public ListAdapter(Context context, List<RegistryInfoModel.Columns> list) {
            super(context, R.layout.registry_dialog_list_item, list);
            this.list = list;
            this.context = context;
        }


        @Override
        public View getView(int position, View someView, ViewGroup arg2) {

            LayoutInflater inflater = LayoutInflater.from(context);

            if (someView == null) {
                someView = inflater.inflate(R.layout.registry_dialog_list_item, arg2, false);
            }

            TextView text = (TextView) someView.findViewById(R.id.registry_dialog_list_item_text);
            text.setTypeface(Fonts.getRoman(context));
            text.setText(list.get(position).getLabel());

            ImageView icon = (ImageView) someView.findViewById(R.id.registry_dialog_list_item_icon);
            icon.setImageResource(R.drawable.top_bar_sort);


            if (list.get(position).isShowIcon()) {
                if (list.get(position).isUpIcon()) {
                    icon.setImageResource(R.drawable.top_bar_sort_asc);
                } else {
                    icon.setImageResource(R.drawable.top_bar_sort_desc);
                }
            }

                return someView;
            }

    }
}
