/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.aaa;

import java.util.Calendar;
import java.util.Date;

/**
 * Utility class for working with Microsoft Active Directory.
 *
 * @author Alex Leigh
 */
public class ActiveDirectoryUtil {
    private final static long DIFF_NET_JAVA_FOR_DATE_AND_TIMES = 11644473600000L;
    private final static long DIFF_NET_JAVA_FOR_DATES = 11644473600000L + 24 * 60 * 60 * 1000;
    private final static int ONE_HUNDRED_NANOSECOND = 10000000;
    private final static long SECONDS_IN_DAY = 86400;

    public static Date getDateFrom(final String adDateStr) {
        final long adDate = Long.parseLong(adDateStr);
        final long milliseconds = (adDate / 10000) - DIFF_NET_JAVA_FOR_DATES;
        final Date date = new Date(milliseconds);
        return date;
    }

    public static Date getDateTimeFrom(final String adDateTimeStr) {
        final long adDateTime = Long.parseLong(adDateTimeStr);
        final long milliseconds = (adDateTime / 10000) - DIFF_NET_JAVA_FOR_DATE_AND_TIMES;
        final Date date = new Date(milliseconds);
        return date;
    }

    public static int getNumberOfDays(final String oneHundredNanosecondInterval) {
        final long interval = Math.abs(Long.parseLong(oneHundredNanosecondInterval));
        final long intervalSecs = interval / ONE_HUNDRED_NANOSECOND;
        final int intervalDays = (int) (intervalSecs / SECONDS_IN_DAY);
        return intervalDays;
    }

    public static Date truncTimeFrom(final Date date) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    public static Date addDaysToDate(final int daysToAdd, final Date date) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, daysToAdd);
        return cal.getTime();
    }
}
