/**
 * Copyright (C) 2015 ogaclejapan
 * Copyright (C) 2013 The Android Open Source Project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zxhl.cms.widget;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.view.MarginLayoutParamsCompat;
import androidx.core.view.ViewCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.zxhl.cms.R;
import com.zxhl.cms.net.SettingPreference;
import com.zxhl.cms.utils.Utils;


public class TabPagerIndicator extends HorizontalScrollView {

    private static final int TITLE_OFFSET_AUTO_CENTER = -1;
    protected final TabLayout tabStrip;
    private int titleOffset;
    private int tabViewBackgroundResId;

    private int tabViewTextColor;
    private float tabViewTextSize;
    private int tabViewTextHorizontalPadding;
    private int tabViewTextMinWidth;
    private int tabViewTextTopMargin;
    private ViewPager viewPager;
    private ViewPager.OnPageChangeListener viewPagerPageChangeListener;
    private OnScrollChangeListener onScrollChangeListener;
    private TabProvider tabProvider;
    private InternalTabClickListener internalTabClickListener;
    private OnTabClickListener onTabClickListener;
    private boolean distributeEvenly;
    private TextView mSelectedTab;

    public TabPagerIndicator(Context context) {
        this(context, null);
    }

    public TabPagerIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabPagerIndicator(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // Disable the Scroll Bar
        setHorizontalScrollBarEnabled(false);

        final DisplayMetrics dm = getResources().getDisplayMetrics();
        final float density = dm.density;

        TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.TabPagerIndicator, defStyle, 0);
        this.titleOffset = a.getLayoutDimension(
                R.styleable.TabPagerIndicator_titleOffset, (int) (24 * density));
        this.tabViewBackgroundResId = a.getResourceId(
                R.styleable.TabPagerIndicator_defaultTabBackground, NO_ID);
        this.tabViewTextColor = a.getColor(R.styleable.TabPagerIndicator_defaultTabTextColor, 0xff000000);
        this.tabViewTextSize = a.getDimension(
                R.styleable.TabPagerIndicator_defaultTabTextSize, TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_SP, 12, dm));
        this.tabViewTextTopMargin = a.getDimensionPixelSize(R.styleable.TabPagerIndicator_defaultTabTextTopMargin, (int) (10 * density));
        this.tabViewTextHorizontalPadding = a.getDimensionPixelSize(
                R.styleable.TabPagerIndicator_defaultTabTextHorizontalPadding, (int) (16 * density));
        this.tabViewTextMinWidth = a.getDimensionPixelSize(
                R.styleable.TabPagerIndicator_defaultTabTextMinWidth, 0);
        this.internalTabClickListener = new InternalTabClickListener();
        this.distributeEvenly = a.getBoolean(
                R.styleable.TabPagerIndicator_distributeEvenly, false);
        a.recycle();

        this.tabStrip = new TabLayout(context, attrs);

        if (distributeEvenly && tabStrip.isIndicatorAlwaysInCenter()) {
            throw new UnsupportedOperationException(
                    "'distributeEvenly' and 'indicatorAlwaysInCenter' both use does not support");
        }

        // Make sure that the Tab Strips fills this View
        setFillViewport(!tabStrip.isIndicatorAlwaysInCenter());

        addView(tabStrip, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (onScrollChangeListener != null) {
            onScrollChangeListener.onScrollChanged(l, oldl);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (tabStrip.isIndicatorAlwaysInCenter() && tabStrip.getChildCount() > 0) {
            // make title always in center
            View firstTab = tabStrip.getChildAt(0);
            View lastTab = tabStrip.getChildAt(tabStrip.getChildCount() - 1);
            int start = (w - Utils.getMeasuredWidth(firstTab)) / 2 - Utils.getMarginStart(firstTab);
            int end = (w - Utils.getMeasuredWidth(lastTab)) / 2 - Utils.getMarginEnd(lastTab);
            tabStrip.setMinimumWidth(tabStrip.getMeasuredWidth());
            ViewCompat.setPaddingRelative(this, start, getPaddingTop(), end, getPaddingBottom());
            setClipToPadding(false);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        // Ensure first scroll
        if (changed && viewPager != null) {
            scrollToTab(viewPager.getCurrentItem(), 0);
        }
    }

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        viewPagerPageChangeListener = listener;
    }

    public void setOnScrollChangeListener(OnScrollChangeListener listener) {
        onScrollChangeListener = listener;
    }

    /**
     * Set {@link OnTabClickListener} for obtaining click event.
     *
     * @param listener the {@link OnTabClickListener} to set
     */
    public void setOnTabClickListener(OnTabClickListener listener) {
        onTabClickListener = listener;
    }


    /**
     * Set the custom layout to be inflated for the tab views.
     *
     * @param provider {@link TabProvider}
     */
    public void setCustomTabView(TabProvider provider) {
        tabProvider = provider;
    }

    /**
     * Sets the associated view pager. Note that the assumption here is that the pager content
     * (number of tabs and tab titles) does not change after this call has been made.
     */
    public void setViewPager(ViewPager viewPager) {
        tabStrip.removeAllViews();

        if (this.viewPager == viewPager)
            populateTabStrip();
        else {
            this.viewPager = viewPager;
            if (viewPager != null && viewPager.getAdapter() != null) {
                viewPager.addOnPageChangeListener(new InternalViewPagerListener());
                populateTabStrip();
            }
        }
    }

    /**
     * Returns the view at the specified position in the tabs.
     *
     * @param position the position at which to get the view from
     * @return the view at the specified position or null if the position does not exist within the
     * tabs
     */
    public View getTabAt(int position) {
        return tabStrip.getChildAt(position);
    }

    /**
     * Create a default view to be used for tabs. This is called if a custom tab view is not set via
     */
    protected View createDefaultTabView(CharSequence title, int position, int count) {
        RelativeLayout view = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.layout_tab_item, null);

        TextView textView = new TextView(getContext());
        textView.setId(R.id.id_tab_text);
        textView.setGravity(Gravity.CENTER);
        textView.setText(title);
        textView.setTextColor(tabViewTextColor);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabViewTextSize);
        textView.setSingleLine();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        textView.setLayoutParams(params);
        if (tabViewTextMinWidth > 0) {
            textView.setMinWidth(tabViewTextMinWidth);
        }

        LinearLayout.LayoutParams viewParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        viewParams.weight = 1;
        viewParams.leftMargin = tabViewTextHorizontalPadding;
        viewParams.rightMargin = tabViewTextHorizontalPadding;
        view.setLayoutParams(viewParams);
        view.addView(textView);

        if (title.equals("幸运抽") && SettingPreference.getIsOpenLuckLottery()) {
            View redView = new View(getContext());
            RelativeLayout.LayoutParams redParams = new RelativeLayout.LayoutParams(com.zxhl.cms.utils.Utils.dip2px(8), com.zxhl.cms.utils.Utils.dip2px(8));
            redParams.addRule(RelativeLayout.RIGHT_OF, textView.getId());
            redParams.addRule(RelativeLayout.ABOVE, textView.getId());
            redParams.bottomMargin = com.zxhl.cms.utils.Utils.dip2px(-6);
            redParams.leftMargin = com.zxhl.cms.utils.Utils.dip2px(2);
            redView.setLayoutParams(redParams);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Drawable drawable = getResources().getDrawable(R.drawable.layer_list_red_dot, null);
                redView.setBackground(drawable);
            }
            view.addView(redView);
        }

        return view;
    }

    private void populateTabStrip() {
        final PagerAdapter adapter = viewPager.getAdapter();

        int current = viewPager.getCurrentItem();
        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {

            final View tabView = (tabProvider == null)
                    ? createDefaultTabView(adapter.getPageTitle(i), i, count)
                    : tabProvider.createTabView(tabStrip, i, adapter);

            if (tabView == null) {
                throw new IllegalStateException("tabView is null.");
            }

            if (distributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            if (internalTabClickListener != null) {
                tabView.setOnClickListener(internalTabClickListener);
            }

            tabStrip.addView(tabView);

            if (i == current) {
                mSelectedTab = (TextView) ((RelativeLayout) tabView).getChildAt(0);
                tabView.setSelected(true);
                mSelectedTab.setTypeface(Typeface.DEFAULT_BOLD);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mSelectedTab.setTextColor(getResources().getColor(R.color.color_4c84ff, null));
                } else {
                    mSelectedTab.setTextColor(getResources().getColor(R.color.color_4c84ff));
                }
            }
        }
    }

    public void setCurrentItem(int index) {
        viewPager.setCurrentItem(index);
        scrollToTab(index, 0);
    }

    private void scrollToTab(int tabIndex, float positionOffset) {
        final int tabStripChildCount = tabStrip.getChildCount();
        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        View selectedTab = ((RelativeLayout) tabStrip.getChildAt(tabIndex)).getChildAt(0);

        if (positionOffset == 0) {
            // set title style bold when it has been selected
            if (mSelectedTab != null && mSelectedTab != selectedTab) {
                mSelectedTab.setTypeface(Typeface.DEFAULT);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mSelectedTab.setTextColor(getResources().getColor(R.color.color_333333, null));
                } else {
                    mSelectedTab.setTextColor(getResources().getColor(R.color.color_333333));
                }
            }
            mSelectedTab = (TextView) selectedTab;
            mSelectedTab.setTypeface(Typeface.DEFAULT_BOLD);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mSelectedTab.setTextColor(getResources().getColor(R.color.color_4c84ff, null));
            } else {
                mSelectedTab.setTextColor(getResources().getColor(R.color.color_4c84ff));
            }
        }

        int widthPlusMargin = Utils.getWidth(selectedTab) + Utils.getMarginHorizontally(selectedTab);
        int extraOffset = (int) (positionOffset * widthPlusMargin);

        if (tabStrip.isIndicatorAlwaysInCenter()) {

            if (0f < positionOffset && positionOffset < 1f) {
                View nextTab = tabStrip.getChildAt(tabIndex + 1);
                int selectHalfWidth = Utils.getWidth(selectedTab) / 2 + Utils.getMarginEnd(selectedTab);
                int nextHalfWidth = Utils.getWidth(nextTab) / 2 + Utils.getMarginStart(nextTab);
                extraOffset = Math.round(positionOffset * (selectHalfWidth + nextHalfWidth));
            }

            View firstTab = tabStrip.getChildAt(0);
            int first = Utils.getWidth(firstTab) + Utils.getMarginStart(firstTab);
            int selected = Utils.getWidth(selectedTab) + Utils.getMarginStart(selectedTab);
            int x = Utils.getStart(selectedTab) - Utils.getMarginStart(selectedTab) + extraOffset - (first - selected) / 2;

            scrollTo(x, 0);
            return;
        }

        int x;
        if (titleOffset == TITLE_OFFSET_AUTO_CENTER) {

            if (0f < positionOffset && positionOffset < 1f) {
                View nextTab = tabStrip.getChildAt(tabIndex + 1);
                int selectHalfWidth = Utils.getWidth(selectedTab) / 2 + Utils.getMarginEnd(selectedTab);
                int nextHalfWidth = Utils.getWidth(nextTab) / 2 + Utils.getMarginStart(nextTab);
                extraOffset = Math.round(positionOffset * (selectHalfWidth + nextHalfWidth));
            }
            x = Utils.getWidthWithMargin(selectedTab) / 2 - getWidth() / 2 + Utils.getPaddingStart(this);

        } else {

            x = (tabIndex > 0 || positionOffset > 0) ? -titleOffset : 0;
        }

        int start = Utils.getStart(selectedTab);
        int startMargin = Utils.getMarginStart(selectedTab);
        x += start - startMargin + extraOffset;

        scrollTo(x, 0);
    }

    /**
     * Allows complete control over the colors drawn in the tab layout. Set with
     */
    public interface TabColorizer {

        /**
         * @return return the color of the indicator used when {@code position} is selected.
         */
        int getIndicatorColor(int position);

        /**
         * @return return the color of the divider drawn to the right of {@code position}.
         */
        int getDividerColor(int position);

    }

    /**
     * Interface definition for a callback to be invoked when the scroll position of a view changes.
     */
    public interface OnScrollChangeListener {

        /**
         * Called when the scroll position of a view changes.
         *
         * @param scrollX    Current horizontal scroll origin.
         * @param oldScrollX Previous horizontal scroll origin.
         */
        void onScrollChanged(int scrollX, int oldScrollX);
    }


    public interface OnTabClickListener {
        void onTabClicked(int position);
    }

    /**
     * Create the custom tabs in the tab layout. Set with
     * {@link #setCustomTabView(TabPagerIndicator.TabProvider)}
     */
    public interface TabProvider {

        /**
         * @return Return the View of {@code position} for the Tabs
         */
        View createTabView(ViewGroup container, int position, PagerAdapter adapter);
    }


    private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {

        private int scrollState;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int tabStripChildCount = tabStrip.getChildCount();
            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            tabStrip.onViewPagerPageChanged(position, positionOffset);

            scrollToTab(position, positionOffset);

            if (viewPagerPageChangeListener != null) {
                viewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            scrollState = state;

            if (viewPagerPageChangeListener != null) {
                viewPagerPageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (scrollState == ViewPager.SCROLL_STATE_IDLE) {
                tabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }

            for (int i = 0, size = tabStrip.getChildCount(); i < size; i++) {
                tabStrip.getChildAt(i).setSelected(position == i);
            }

            if (viewPagerPageChangeListener != null) {
                viewPagerPageChangeListener.onPageSelected(position);
            }
        }

    }

    private class InternalTabClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < tabStrip.getChildCount(); i++) {
                if (v == tabStrip.getChildAt(i)) {
                    if (onTabClickListener != null) {
                        onTabClickListener.onTabClicked(i);
                    }
                    viewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    }

    static class Utils {

        static int getMeasuredWidth(View v) {
            return (v == null) ? 0 : v.getMeasuredWidth();
        }

        static int getWidth(View v) {
            return (v == null) ? 0 : v.getWidth();
        }

        static int getWidthWithMargin(View v) {
            return getWidth(v) + getMarginHorizontally(v);
        }

        static int getStart(View v) {
            return getStart(v, false);
        }

        static int getStart(View v, boolean withoutPadding) {
            if (v == null) {
                return 0;
            }
            return (withoutPadding) ? v.getLeft() + getPaddingStart(v) : v.getLeft();
        }

        static int getEnd(View v) {
            return getEnd(v, false);
        }

        static int getEnd(View v, boolean withoutPadding) {
            if (v == null) {
                return 0;
            }
            return (withoutPadding) ? v.getRight() - getPaddingEnd(v) : v.getRight();
        }

        static int getPaddingStart(View v) {
            if (v == null) {
                return 0;
            }
            return ViewCompat.getPaddingStart(v);
        }

        static int getPaddingEnd(View v) {
            if (v == null) {
                return 0;
            }
            return ViewCompat.getPaddingEnd(v);
        }

        static int getPaddingHorizontally(View v) {
            if (v == null) {
                return 0;
            }
            return v.getPaddingLeft() + v.getPaddingRight();
        }

        static int getMarginStart(View v) {
            if (v == null) {
                return 0;
            }
            MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
            return MarginLayoutParamsCompat.getMarginStart(lp);
        }

        static int getMarginEnd(View v) {
            if (v == null) {
                return 0;
            }
            MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
            return MarginLayoutParamsCompat.getMarginEnd(lp);
        }

        static int getMarginHorizontally(View v) {
            if (v == null) {
                return 0;
            }
            MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
            return MarginLayoutParamsCompat.getMarginStart(lp) + MarginLayoutParamsCompat.getMarginEnd(lp);
        }

        static float getDimen(Resources Resources, int id) {
            return Resources.getDimension(id);
        }

        static int getDimenPx(Resources Resources, int id) {
            return Resources.getDimensionPixelSize(id);
        }
    }
}
