# -*- coding: utf-8 -*-
# Copyright (c) 2017 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com


from datetime import datetime
from decimal import ROUND_DOWN, Decimal
from time import time
from typing import SupportsFloat

from dateutil.parser import parse
from dateutil.tz import tzutc


def parse_to_utc(iso_date: str) -> datetime:
    if not iso_date:
        raise TypeError(f'Invalid iso_date: "{iso_date}"')
    return parse(iso_date).replace(tzinfo=tzutc())


def parse_to_utc_timestamp(iso_date: str) -> Decimal:
    if not iso_date or not type(iso_date) is str:
        raise TypeError(f'Invalid iso_date: "{iso_date}"')
    return Decimal(f'{parse_to_utc(iso_date).timestamp():.4f}')


def timestamp_to_utc_datetime(timestamp: SupportsFloat) -> datetime:
    if not timestamp:
        raise TypeError(f'Invalid timestamp: "{timestamp}"')
    return datetime.fromtimestamp(float(timestamp), tz=tzutc())


def timestamp_to_utc_iso(timestamp: SupportsFloat) -> str:
    if not timestamp:
        raise TypeError(f'Invalid timestamp: "{timestamp}"')
    return timestamp_to_utc_datetime(timestamp).isoformat()


def get_current_timestamp() -> Decimal:
    return Decimal(str(time())).quantize(Decimal(".00000"), rounding=ROUND_DOWN)


# Legacy API
iso_string_to_utc_datetime = parse_to_utc
iso_string_to_timestamp = parse_to_utc_timestamp
timestamp_to_iso_string = timestamp_to_utc_iso
