# -*- coding: utf-8 -*-
import datetime
import random
from enum import Enum


class TtlCache(object):

    class Status(Enum):
        ABSENT = 0
        EXPIRED = 1
        OK = 2

    def __init__(self, ttl_in_seconds=120, with_random=True):
        """

        """
        self._data = {}
        random_shift = 0

        if with_random:
            random_shift = random.randint(1, 120)
        self._delta = datetime.timedelta(seconds=ttl_in_seconds + random_shift)
        # self._lock = Lock()

    @staticmethod
    def _get_current_timestamp():
        return datetime.datetime.now()

    def insert(self, key, val):
        print('TtlCach miss {}'.format(key))
        self._data[key] = (val, self._get_current_timestamp())

    def get(self, key):
        if key not in self._data:
            return self.Status.ABSENT, None
        rec, timestamp = self._data[key]
        if self._get_current_timestamp() - timestamp > self._delta:
            return self.Status.EXPIRED, rec
        return self.Status.OK, rec
