# encoding: utf-8
from datetime import timedelta, datetime

__copyright__ = "Copyright (C) 2015 University of Wisconsin SSEC. All rights reserved."

from astropy.time import Time, TimeDelta


def unixtime(dt):
    """
    Datetime to Unix timestamp.
    """
    return (dt - datetime(1970, 1, 1)).total_seconds()


def cds_to_dt(days, millis, microseconds):
    """
    CCSDS Day Segmented timecode to UTC datetime.
    """
    return datetime(1970, 1, 1) + timedelta(days=days, microseconds=1e6 * millis + microseconds)


def cds_to_iet(days, ms, us):
    """
    CCSDS Day Segmented timecode parts to IET (microseconds)
    """
    iet_epoch = Time('1958-01-01', scale='tai')
    ccsds_epoch = Time('1958-01-01', scale='tai')
    day = Time(ccsds_epoch.jd + days, scale='utc', format='jd') - iet_epoch
    return int(day.sec * 1e6 + ms * 1e3 + us)