# coding=utf-8
from __future__ import unicode_literals

import re
import time
import datetime

from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
from django.utils import timezone


def get_timestamp_epoch(the_time):
    if the_time is None:
        return None

    if isinstance(the_time, datetime.datetime):
        pass
    elif isinstance(the_time, datetime.date):
        # TODO: 是这样算的么？
        the_time = datetime.datetime(
            the_time.year, the_time.month, the_time.day)
    else:
        raise TypeError(
            "datetime.datetime or datetime.date expected. [%s]" % type(the_time))
    return int((the_time - datetime.datetime.fromtimestamp(0)).total_seconds())


def get_timestamp(the_time):
    if the_time is None:
        return None
    return get_timestamp_epoch(the_time) + 8 * 3600


def get_datetime(the_time):
    return datetime.datetime.utcfromtimestamp(the_time)


def get_timestamp_or_none(the_time):
    return get_timestamp(the_time) if the_time is not None else None


def get_strftime(the_time):
    if isinstance(the_time, datetime.datetime):
        return the_time.strftime('%Y-%m-%d')

    return str(the_time)


def ts_now_as_score():
    return int(time.mktime(timezone.now().timetuple()))


def get_monday(day=None):
    """
    返回输入日期的当星期的星期一的日期
    :param day: 输入日期
    :return: 输入日期的星期的星期一
    """
    if not day:
        day = datetime.date.today()
    return day + relativedelta(weekday=MO(-1))


def get_humanize_datetime(d):
    """humanize datetime
    """
    now = datetime.datetime.now()

    if d.year == now.year:
        if d.month == now.month:
            if d.day == now.day:
                return u'今天'
            else:
                return u'{}天前'.format(now.day - d.day)
        else:
            return d.strftime('%m-%d')
    else:
        return d.strftime('%Y-%m-%d')


def get_seconds_left_to_end_of_day():
    now = timezone.now()
    end_of_day = datetime.datetime.combine(now, datetime.time.max)
    time_delta = end_of_day - now
    return int(time_delta.total_seconds())


def add_month(dt, n):
    return datetime.date(
        dt.year + (dt.month + n - 1) / 12,
        (dt.month + n) % 12 or 12,
        dt.day,
    )


def add_day(dt, n):
    return dt + datetime.timedelta(days=n)


def itv2time(iItv):
    """
    将秒 转化为 时:分:秒字符串
    :param iItv: 2342347
    :return: 23:23:23
    """
    iItv = int(iItv)
    if type(iItv) != type(1):
        return ""
    h = iItv / 3600
    sUp_h = iItv - 3600 * h
    m = sUp_h / 60
    sUp_m = sUp_h - 60 * m
    s = sUp_m
    return ":".join(list(map(lambda x: str(x).zfill(2) if len(str(x)) != 2 else str(x), [h, m, s])))

