#  Copyright (C) 2022
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Vasya Svintsov <v.svintsov@techokert.ru>

from dataclasses import dataclass
from types import TracebackType
from typing import Optional

import time


@dataclass
class Timer:
    start: Optional[float] = None
    end: Optional[float] = None

    @property
    def duration(self) -> Optional[float]:
        return None if (self.end is None or self.start is None) else self.end - self.start

    def __enter__(self) -> 'Timer':
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None:
        self.end = time.time()

    async def __aenter__(self) -> 'Timer':
        return self.__enter__()

    async def __aexit__(self, exc_type, exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None:
        return self.__exit__(exc_type, exc_val, exc_tb)
