/*
 * 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.util;

import java.util.Date;

/**
 * This object is a composite of a <code>java.util.Date</code> and a separate
 * nanoseconds value. Only integral seconds are stored in the
 * <code>java.util.Date</code> component. The fractional seconds - the nanos -
 * are separate.
 */

public final class Timestamp extends Date {
    private static final long serialVersionUID = 1L;

    private int nanos = 0;

    /**
     * This method initializes a new instance of this class with the time value
     * set to the current system time.
     */
    public Timestamp() {
    }

    /**
     * This method initializes a new instance of this class with the specified
     * time value representing the number of milliseconds since Jan 1, 1970 at
     * 12:00 midnight GMT.
     */
    public Timestamp(final long date) {
        super(date - (date % 1000));
        nanos = (int) (date % 1000) * 1000000;
    }

    public Timestamp(final String s) {
        final String[] fields = s.split("\\.");
        setTime(Long.parseLong(fields[0]));
        if (fields.length == 2) {
            setNanos(Integer.parseInt(fields[1]));
        }
    }

    /**
     * This method returns the nanosecond value for this <code>Timestamp</code>.
     *
     * @return The nanosecond value for this object.
     */
    public int getNanos() {
        return nanos;
    }

    /**
     * This method sets the nanosecond value for this <code>Timestamp</code>.
     *
     * @param nanos The nanosecond value of this object.
     */
    void setNanos(final int nanos) {
        this.nanos = nanos;
    }

    /**
     * Return the value of this <code>Timestamp</code> as the number of
     * milliseconds since Jan 1, 1970 at 12:00 midnight GMT.
     */
    @Override
    public long getTime() {
        return super.getTime() + (nanos / 1000000);
    }

    /**
     * This method returns a String representing a formatted version of this
     * <code>Timestamp</code>. The format is %l.%l with the first component
     * representing the number of milliseconds since Jan 1, 1970 at 12:00
     * midnight GMT, and the second part containing the remainder in
     * nanoseconds.
     */
    @Override
    public String toString() {
        return super.getTime() + "." + nanos;
    }

    /**
     * This method returns the time for this <code>Timestamp</code> in
     * "unixtime" format, which represents the number of seconds since Jan 1,
     * 1970 at 12:00 midnight GMT.
     */
    public long toUnixtime() {
        return super.getTime() / 1000;
    }
}
