package ru.yandex.webmaster3.viewer.http.searchurl.filter;

import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import ru.yandex.webmaster3.core.http.RequestFilter;
import ru.yandex.webmaster3.core.http.request.RequestContext;

/**
 * @author avhaliullin
 */
public class SearchUrlDateRangeFilter implements RequestFilter<SearchUrlDateRangeAware, SearchUrlDateRangeFilterResponse> {
    public static final int MAXIMUM_RANGE_IN_MONTH = 36;

    @Override
    public SearchUrlDateRangeFilterResponse beforeRequest(RequestContext ctx, SearchUrlDateRangeAware req) {
        Instant now = Instant.now();
        Instant dateFrom = req.getDateFrom();
        Instant dateTo = req.getDateTo();

        if (dateFrom != null) {
            if (dateFrom.isAfter(now)) {
                return new SearchUrlDateRangeFilterResponse.IllegalDateRange(this.getClass(),
                        "dateFrom",
                        dateFrom.toString());
            }
        }
        if (dateTo != null) {
            if (dateTo.isAfter(now)) {
                return new SearchUrlDateRangeFilterResponse.IllegalDateRange(this.getClass(),
                        "dateTo",
                        dateTo.toString());
            }
        }
        if (dateFrom != null && dateTo != null) {
            if (Months.monthsBetween(dateFrom, dateTo).getMonths() > MAXIMUM_RANGE_IN_MONTH) {
                return new SearchUrlDateRangeFilterResponse.IllegalDateRange(this.getClass(),
                        "dateFrom",
                        dateFrom.toString());
            }
        }
        return null;
    }
}
