package com.its.web.pagination;

import lombok.Data;

import java.util.List;

@Data
public class Pagination {
    private static final int PAGE_PER_NUM = 10;
    private int startRow;
    private int endRow;
    private int currentPage;
    private int startPage;
    private int endPage;
    private int totalPage;
    private int prevPage;
    private int nextPage;
    private String searchType;
    private String searchText;
    private List<?> list;

    public Pagination (String page, int totalCount, String searchType, String searchText) {
        this.currentPage = 1;
        this.startPage = 1;
        this.endPage = 1;
        this.totalPage = 1;
        this.prevPage = 0;
        this.nextPage = 0;
        this.searchType = "";
        this.searchText = "";

        if (searchText != null && !searchText.isEmpty()) {
            this.searchText = searchText;
        }

        if (searchType != null && !searchType.isEmpty()) {
            this.searchType = searchType;
        }

        try {
            if (Integer.parseInt(page) > 0) {
                this.currentPage = Integer.parseInt(page);
            }
        }
        catch (NumberFormatException e) {

        }

        if (totalCount > PAGE_PER_NUM){
            this.totalPage = totalCount / PAGE_PER_NUM;
            if (totalCount % PAGE_PER_NUM > 0) {
                this.totalPage++;
            }
        }

        if (this.totalPage < this.currentPage) {
            this.currentPage = this.totalPage;
        }

        this.startPage = ((this.currentPage-1) / PAGE_PER_NUM) * PAGE_PER_NUM + 1;
        this.endPage = this.startPage + PAGE_PER_NUM - 1;

        if (this.endPage > this.totalPage) {
            this.endPage = this.totalPage;
        }

        if (this.startPage > PAGE_PER_NUM) {
            this.prevPage = this.startPage - PAGE_PER_NUM;
        }

        if (this.totalPage > PAGE_PER_NUM && this.endPage < this.totalPage) {
            this.nextPage = this.endPage + 1;
        }

        this.startRow = (this.currentPage - 1) * PAGE_PER_NUM + 1;
        this.endRow = this.startRow + PAGE_PER_NUM -1;
        if (totalCount < this.endRow + 1) {
            this.endRow = totalCount;
        }
    }
}
