/*
 * Copyright 2010-2013 Ning, Inc.
 *
 * Ning licenses this file to you 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.killbill.billing.entitlement.api;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;

import org.killbill.billing.account.api.Account;
import org.killbill.billing.account.api.AccountApiException;
import org.killbill.billing.account.api.AccountInternalApi;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.clock.Clock;

public class EntitlementDateHelper {

    private final AccountInternalApi accountApi;
    private final Clock clock;

    public EntitlementDateHelper(final AccountInternalApi accountApi, final Clock clock) {
        this.accountApi = accountApi;
        this.clock = clock;
    }

    public DateTime fromNowAndReferenceTime(final DateTime referenceDateTime, final InternalTenantContext callContext) throws EntitlementApiException {
        try {
            final Account account = accountApi.getAccountByRecordId(callContext.getAccountRecordId(), callContext);
            return fromNowAndReferenceTime(referenceDateTime, account.getTimeZone());
        } catch (AccountApiException e) {
            throw new EntitlementApiException(e);
        }
    }

    public DateTime fromNowAndReferenceTime(final DateTime referenceDateTime, final DateTimeZone accountTimeZone) {
        final LocalDate localDateNowInAccountTimezone = new LocalDate(clock.getUTCNow(), accountTimeZone);
        return fromLocalDateAndReferenceTime(localDateNowInAccountTimezone, referenceDateTime, accountTimeZone);
    }

    public DateTime fromLocalDateAndReferenceTime(final LocalDate requestedDate, final DateTime referenceDateTime, final InternalTenantContext callContext) throws EntitlementApiException {
        try {
            final Account account = accountApi.getAccountByRecordId(callContext.getAccountRecordId(), callContext);
            return fromLocalDateAndReferenceTime(requestedDate, referenceDateTime, account.getTimeZone());
        } catch (AccountApiException e) {
            throw new EntitlementApiException(e);
        }
    }

    public DateTime fromLocalDateAndReferenceTime(final LocalDate requestedDate, final DateTime referenceDateTime, final DateTimeZone accountTimeZone) {
        final LocalDate localDateNowInAccountTimezone = new LocalDate(requestedDate, accountTimeZone);
        // Datetime from local date in account timezone and with given reference time
        final DateTime t1 = localDateNowInAccountTimezone.toDateTime(referenceDateTime.toLocalTime(), accountTimeZone);
        // Datetime converted back in UTC
        final DateTime t2 = new DateTime(t1, DateTimeZone.UTC);

        //
        // Ok, in the case of a LocalDate of today we expect any change to be immediate, so we check that DateTime returned is not in the future
        // (which means that reference time might not be honored, but this is not very important).
        //
        return adjustDateTimeToNotBeInFutureIfLocaDateIsToday(t2, accountTimeZone);
    }

    private DateTime adjustDateTimeToNotBeInFutureIfLocaDateIsToday(final DateTime inputUtc, final DateTimeZone accountTimeZone) {
        // If the LocalDate is TODAY but after adding the reference time we end up in the future, we correct it to be NOW,
        // so change occurs immediately.
        // If the LocalDate is TODAY but after adding the reference time we end up in the past, we also correct it to NOW,
        // so we don't end up having events between this time and NOW.
        // Note that in both these cases, we won't respect the reference time.
        if (isEqualsToday(inputUtc, accountTimeZone)) {
            return clock.getUTCNow();
        } else {
            return inputUtc;
        }
    }

    /**
     * Check if the date portion of a date/time is equals at today (as returned by the clock).
     *
     * @param inputDate       the fully qualified DateTime
     * @param accountTimeZone the account timezone
     * @return true if the inputDate, once converted into a LocalDate using account timezone is equals at today
     */
    private boolean isEqualsToday(final DateTime inputDate, final DateTimeZone accountTimeZone) {
        final LocalDate localDateNowInAccountTimezone = new LocalDate(clock.getUTCNow(), accountTimeZone);
        final LocalDate targetDateInAccountTimezone = new LocalDate(inputDate, accountTimeZone);

        return targetDateInAccountTimezone.compareTo(localDateNowInAccountTimezone) == 0;
    }

    /**
     * Check if the date portion of a date/time is before or equals at now (as returned by the clock).
     *
     * @param inputDate       the fully qualified DateTime
     * @param accountTimeZone the account timezone
     * @return true if the inputDate, once converted into a LocalDate using account timezone is less or equals than today
     */
    public boolean isBeforeOrEqualsToday(final DateTime inputDate, final DateTimeZone accountTimeZone) {
        final LocalDate localDateNowInAccountTimezone = new LocalDate(clock.getUTCNow(), accountTimeZone);
        final LocalDate targetDateInAccountTimezone = new LocalDate(inputDate, accountTimeZone);

        return targetDateInAccountTimezone.compareTo(localDateNowInAccountTimezone) <= 0;
    }
}

@@ -730,16 +730,47 @@
 meZone;%0A
+import org.joda.time.Interval;%0A
 import o
@@ -1059,16 +1059,53 @@
 k.Clock;
+%0Aimport org.killbill.clock.ClockUtil;
 %0A%0Apublic
@@ -1409,3722 +1409,577 @@
 from
-NowAndReferenceTime(final DateTime referenceDateTime, final InternalTenantContext callContext) throws EntitlementApiException %7B%0A        try %7B%0A            final Account account = accountApi.getAccountByRecordId(callContext.getAccountRecordId(), callContext);%0A            return fromNowAndReferenceTime(referenceDateTime, account.getTimeZone());%0A        %7D catch (AccountApiException e) %7B%0A            throw new EntitlementApiException(e);%0A        %7D%0A    %7D%0A%0A    public DateTime fromNowAndReferenceTime(final DateTime referenceDateTime, final DateTimeZone accountTimeZone) %7B%0A        final LocalDate localDateNowInAccountTimezone = new LocalDate(clock.getUTCNow(), accountTimeZone);%0A        return fromLocalDateAndReferenceTime(localDateNowInAccountTimezone, referenceDateTime, accountTimeZone);%0A    %7D%0A%0A    public DateTime fromLocalDateAndReferenceTime(final LocalDate requestedDate, final DateTime referenceDateTime, final InternalTenantContext callContext) throws EntitlementApiException %7B%0A        try %7B%0A            final Account account = accountApi.getAccountByRecordId(callContext.getAccountRecordId(), callContext);%0A            return fromLocalDateAndReferenceTime(requestedDate, referenceDateTime, account.getTimeZone());%0A        %7D catch (AccountApiException e) %7B%0A            throw new EntitlementApiException(e);%0A        %7D%0A    %7D%0A%0A    public DateTime fromLocalDateAndReferenceTime(final LocalDate requestedDate, final DateTime referenceDateTime, final DateTimeZone accountTimeZone) %7B%0A        final LocalDate localDateNowInAccountTimezone = new LocalDate(requestedDate, accountTimeZone);%0A        // Datetime from local date in account timezone and with given reference time%0A        final DateTime t1 = localDateNowInAccountTimezone.toDateTime(referenceDateTime.toLocalTime(), accountTimeZone);%0A        // Datetime converted back in UTC%0A        final DateTime t2 = new DateTime(t1, DateTimeZone.UTC);%0A%0A        //%0A        // Ok, in the case of a LocalDate of today we expect any change to be immediate, so we check that DateTime returned is not in the future%0A        // (which means that reference time might not be honored, but this is not very important).%0A        //%0A        return adjustDateTimeToNotBeInFutureIfLocaDateIsToday(t2, accountTimeZone);%0A    %7D%0A%0A    private DateTime adjustDateTimeToNotBeInFutureIfLocaDateIsToday(final DateTime inputUtc, final DateTimeZone accountTimeZone) %7B%0A        // If the LocalDate is TODAY but after adding the reference time we end up in the future, we correct it to be NOW,%0A        // so change occurs immediately.%0A        // If the LocalDate is TODAY but after adding the reference time we end up in the past, we also correct it to NOW,%0A        // so we don't end up having events between this time and NOW.%0A        // Note that in both these cases, we won't respect the reference time.%0A        if (isEqualsToday(inputUtc, accountTimeZone)) %7B%0A            return clock.getUTCNow();%0A        %7D else %7B%0A            return inputUtc;%0A        %7D%0A    %7D%0A%0A    /**%0A     * Check if the date portion of a date/time is equals at today (as returned by the clock).%0A     *%0A     * @param inputDate       the fully qualified DateTime%0A     * @param accountTimeZone the account timezone%0A     * @return true if the inputDate, once converted into a LocalDate using account timezone is equals at today%0A     */%0A    private boolean isEqualsToday(final DateTime inputDate, final DateTimeZone accountTimeZone) %7B%0A        final LocalDate localDateNowInAccountTimezone = new LocalDate(clock.getUTCNow(), accountTimeZone);%0A        final LocalDate targetDateInAccountTimezone = new LocalDate(inputDate, accountTimeZone);%0A%0A        return targetDateInAccountTimezone.compareTo(localDateNowInAccountTimezone) == 0;
+LocalDateAndReferenceTime(final LocalDate requestedDate, final DateTime referenceDateTime, final InternalTenantContext callContext) throws EntitlementApiException %7B%0A        try %7B%0A            final Account account = accountApi.getAccountByRecordId(callContext.getAccountRecordId(), callContext);%0A            return ClockUtil.computeDateTimeWithUTCReferenceTime(requestedDate, referenceDateTime.toDateTime(DateTimeZone.UTC).toLocalTime(), account.getTimeZone(), clock);%0A        %7D catch (AccountApiException e) %7B%0A            throw new EntitlementApiException(e);%0A        %7D
 %0A   
@@ -2340,16 +2340,47 @@
      */%0A
+    // TODO Move to ClockUtils%0A
     publ
@@ -2680,17 +2680,16 @@
 eZone);%0A
-%0A
         

Refactor EntitlementDateHelper to use new ClockUtils