# Copyright (c) 2005 Infrae. All rights reserved.
# See also LICENSE.txt
import pytz
from datetime import datetime
from zope.app import zapi
from documentlibrary.core import interfaces

def _documentlibrary_timezone():
    name = zapi.getUtility(interfaces.ITimezone).timezone_name
    return pytz.timezone(name)

def toUTC(dt_tz):
    """Convert timezone-aware datetime to datetime in the UTC timezone.
    """
    assert dt_tz.tzinfo is not None
    return dt_tz.astimezone(pytz.timezone('UTC'))

def toNaiveUTC(dt_tz):
    """Convert timezone-aware datetime to datetime in the UTC timezone and
    strip the timezone info.
    """
    return toUTC(dt_tz).replace(tzinfo=None)

def nowInUTC():
    """Return 'now' in the UTC timezone.
    """
    return datetime.now(pytz.utc)

def inUTC(dt):
    """Add UTC timezone information to timezone naive datetime.
    """
    assert dt.tzinfo is None
    return dt.replace(tzinfo=pytz.timezone('UTC'))

def startOfDay():
    """Return the UTC representation of the Document Library's start of day.
    """
    dl_start_of_day = datetime.now(_documentlibrary_timezone()).replace(
        hour=0, minute=0, second=0)
    return toUTC(dl_start_of_day)

def forDisplay(dt_tz):
    """Convert timezone-aware datetime to datetime in the 
    Document Library timezone.
    """
    assert dt_tz.tzinfo is not None
    return dt_tz.astimezone(_documentlibrary_timezone())

def fromInput(dt):
    """Convert naive datetime to datetime in the UTC timezone, using the 
    Document Library timezone.
    """
    naive_dt = datetime(
        dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
    local_dt = _documentlibrary_timezone().localize(naive_dt)
    return toUTC(local_dt)
