package com.luticate.utils.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import com.luticate.utils.business.LuPromise;

import java.util.List;
import java.util.Vector;

/**
 * Created by robin on 12/8/15.
 */
public abstract class AbstractPaginationView extends LinearLayout {

    private LuPromise.LuConsumer<Integer> _onPageChanged = null;

    private int _page = 0;

    private int _maxPage = 1;

    private int _contextPagesCount = 2;

    public AbstractPaginationView(Context context) {
        super(context);
        init();
    }

    public AbstractPaginationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public AbstractPaginationView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs)
    {
        init();
        //_contextPagesCount = attrs.getAttributeIntValue(R.styleable.DefaultPaginationView_contextPagesCount, _contextPagesCount);
    }

    private void init()
    {

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (isInEditMode())
        {
            onUpdatePages();
        }
    }

    protected List<Integer> getPages()
    {
        List<Integer> pages = new Vector<>();
        int start = Math.max(0, getPage() - getContextPagesCount());
        int end = Math.min(start + getContextPagesCount() + 1, getMaxPage());
        for (int i = start; i < end; ++i)
        {
            pages.add(i);
        }
        return pages;
    }

    protected abstract void onUpdatePages();

    public int getMaxPage() {
        return isInEditMode() ? 50 : _maxPage;
    }

    public void setMaxPage(int maxPage) {
        _maxPage = maxPage;
        onUpdatePages();
    }

    public int getContextPagesCount() {
        return _contextPagesCount;
    }

    public void setContextPagesCount(int contextPagesCount) {
        _contextPagesCount = contextPagesCount;
        onUpdatePages();
    }

    public void setPage(int page)
    {
        _page = page;
        onUpdatePages();
    }

    public int getPage()
    {
        return isInEditMode() ? 24 : _page;
    }

    public void setOnPageChanged(LuPromise.LuConsumer<Integer> onPageChanged) {
        _onPageChanged = onPageChanged;
    }

    public void loadPage(int page)
    {
        if (_onPageChanged != null)
        {
            _onPageChanged.execute(page);
        }
    }

    public void loadNextPage()
    {
        int page = getPage();
        if (page < getMaxPage() - 1)
        {
            loadPage(page + 1);
        }
    }

    public void loadPreviousPage()
    {
        int page = getPage();
        if (page > 0)
        {
            loadPage(page - 1);
        }
    }
}
