package ru.yandex.webmaster.common.http.response;

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

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

/**
 * @author aherman
 */
@JacksonXmlRootElement(localName = "pager")
public class OldPager {
    private static final int PAGES_LENGTH = 7;
    private static final int DEFAULT_PAGE_SIZE = 25;

    private final int currentPage;
    private final int itemsCount;
    private final int pageSize;
    private final boolean showAll;
    private final int totalPagesCount;

    public OldPager(int currentPage, int pageSize, int itemsCount, boolean showAll) {
        this.itemsCount = itemsCount;
        this.showAll = showAll;

        if (showAll) {
            this.pageSize = Math.max(itemsCount, 1);
        } else {
            this.pageSize = pageSize > 0 ? pageSize : DEFAULT_PAGE_SIZE;
        }

        this.totalPagesCount = (itemsCount / this.pageSize) + ((itemsCount % this.pageSize > 0) ? 1 : 0);
        if (currentPage >= this.totalPagesCount) {
            this.currentPage  = Math.max(0, this.totalPagesCount - 1);
        } else {
            this.currentPage = currentPage;
        }
    }

    @JacksonXmlElementWrapper(useWrapping = false, localName = "page")
    public List<Page> getPage() {
        List<Page> result = new ArrayList<>(PAGES_LENGTH * 2);
        for (int i = Math.max(0, currentPage - PAGES_LENGTH);
             i < Math.min(currentPage + PAGES_LENGTH + 1, totalPagesCount); ++i)
        {
            result.add(new Page(i, i == currentPage));
        }
        return result;
    }

    @JacksonXmlProperty(localName = "count", isAttribute = true)
    public int getItemsCount() {
        return itemsCount;
    }

    @JacksonXmlProperty(localName = "page-size", isAttribute = true)
    public int getPageSize() {
        return pageSize;
    }

    @JacksonXmlProperty(localName = "show-all", isAttribute = true)
    public String getShowAll() {
        if (showAll) {
            return "on";
        } else {
            return "";
        }
    }

    @JacksonXmlProperty(localName = "total-page-count", isAttribute = true)
    public int getTotalPagesCount() {
        return totalPagesCount;
    }

    public static class Page {
        private final int num;
        private final boolean current;

        public Page(int num, Boolean current) {
            this.num = num;
            this.current = current;
        }

        @JacksonXmlProperty(isAttribute = true)
        public int getNum() {
            return num;
        }

        @JacksonXmlProperty(isAttribute = true)
        public Boolean getCurrent() {
            if (current) {
                return true;
            } else {
                return null;
            }
        }
    }
}
