import datetime
from django.utils import timezone

ANGLES = {
    'N': (-23, 22),
    'NO': (292, 337),
    'O': (247, 292),
    'SO': (202, 247),
    'S': (157, 202),
    'SE': (112, 157),
    'E': (67, 112),
    'NE': (22, 67)
}

ORIENTATIONS = ANGLES.keys()


def merge_intervals(l, wrap=360):
    """Merge a list of intervals, assuming the space is cyclic.  The
    intervals should already by sorted by start value."""
    if l == []:
        return []
    result = list()
    # Transform the 2-tuple into a 2-list to be able to modify it
    result.append(list(l[0]))
    for (start, stop) in l:
        current = result[-1]
        if start > current[1]:
            result.append([start, stop])
        else:
            result[-1][1] = max(result[-1][1], stop)
    if len(result) == 1:
        return result
    # Handle the cyclicity by merging the ends if necessary
    last = result[-1]
    first = result[0]
    if first[0] <= last[1] - wrap:
        result[-1][1] = max(result[-1][1], first[1] + wrap)
        result.pop(0)
    return result


def add_one_year(date):
    new_day, new_month, new_year = date.day, date.month, date.year + 1

    try:
        new_date = timezone.make_aware(
            datetime.datetime(new_year, new_month, new_day))
    except ValueError:  # Hello 29/3
        new_day -= 1
        new_date = timezone.make_aware(
            datetime.datetime(new_year, new_month, new_day))

    return new_date