/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 org.jboss.pnc.datastore.repositories.internal;

import org.jboss.pnc.datastore.limits.CursoredPageRequest;
import org.jboss.pnc.spi.datastore.repositories.api.PageInfo;
import org.jboss.pnc.spi.datastore.repositories.api.SortInfo;
import org.jboss.pnc.spi.datastore.repositories.api.impl.DefaultPageInfo;
import org.jboss.pnc.spi.datastore.repositories.api.impl.DefaultSortInfo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

public class PageableMapper {

    public static PageRequest map(PageInfo pageInfo, SortInfo sortInfo) {
        return new PageRequest(getPageOffset(pageInfo), getPageSize(pageInfo), getSort(sortInfo));
    }

    public static CursoredPageRequest mapCursored(PageInfo pageInfo, SortInfo sortInfo) {
        return new CursoredPageRequest(getPageOffset(pageInfo), getPageSize(pageInfo), getSort(sortInfo));
    }

    private static Sort getSort(SortInfo sortInfo) {
        if(sortInfo == null) {
            sortInfo = new DefaultSortInfo();
        }
        Sort.Direction direction = sortInfo.getDirection() == SortInfo.SortingDirection.ASC ? Sort.Direction.ASC :
                Sort.Direction.DESC;
        return new Sort(direction, sortInfo.getFields());
    }

    private static int getPageOffset(PageInfo pageInfo) {
        if(pageInfo == null) {
            pageInfo = new DefaultPageInfo();
        }
        return pageInfo.getPageOffset();
    }

    private static int getPageSize(PageInfo pageInfo) {
        if(pageInfo == null) {
            pageInfo = new DefaultPageInfo();
        }
        return pageInfo.getPageSize();
    }
}
