import datetime as xdatetime
import time as xtime

from httpx import AsyncClient

from .btype import Ifs, Null

_server_time: float = xtime.time()
_init_time: float = xtime.monotonic()
_default_time_offset: xdatetime.timedelta = xdatetime.timedelta(hours=8)


async def network_time(time_offset: xdatetime.timedelta = _default_time_offset):
    async with AsyncClient() as client:
        response = await client.get('https://www.baidu.com')
        date_str = response.headers['Date']
        return xdatetime.datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S GMT') + time_offset


async def init_server_datetime(time_offset: xdatetime.timedelta = _default_time_offset):
    global _server_time, _init_time
    _server_time = (await network_time(time_offset)).timestamp()
    _init_time = xtime.monotonic()


def timestamp():
    return _server_time + xtime.monotonic() - _init_time


def timestamp_second():
    return int(timestamp())


def timestamp_millisecond():
    return int(timestamp() * 1000)


def datetime(t: Ifs = Null):
    t = float(t) if t else timestamp()
    return xdatetime.datetime.fromtimestamp(t)


def date(t: Ifs = Null):
    t = float(t) if t else timestamp()
    return xdatetime.date.fromtimestamp(t)


def time(t: Ifs = Null):
    return datetime(t).time()


def datetime_str(t: Ifs = Null, fmt: str = r'%Y-%m-%d %H:%M:%S'):
    return datetime(t).strftime(fmt)


def date_str(t: Ifs = Null, fmt: str = r'%Y-%m-%d'):
    return date(t).strftime(fmt)


def time_str(t: Ifs = Null, fmt: str = r'%H:%M:%S'):
    return time(t).strftime(fmt)


def make_datetime(date_str: str, fmt: str = r'%Y-%m-%d %H:%M:%S'):
    return xdatetime.datetime.strptime(date_str, fmt)


def make_date(date_str: str, fmt: str = r'%Y-%m-%d'):
    return xdatetime.datetime.strptime(date_str, fmt).date()
