# authentic2 - versatile identity manager
# Copyright (C) 2010-2021 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import math
import random
import time

from django.conf import settings
from django.db import connection


def poisson_random(frequency):
    '''Generate random numbers following a poisson distribution'''
    return -math.log(1.0 - random.random()) / frequency


SAFE_GET_OR_CREATE_RETRIES = 3


class ConcurrencyError(Exception):
    pass


def safe_get_or_create(model, defaults=None, **kwargs):
    assert (
        getattr(settings, 'TESTING', False) or not connection.in_atomic_block
    ), 'safe_get_or_create cannot be used in inside a transaction'

    defaults = defaults or {}
    exception = None
    for dummy in range(SAFE_GET_OR_CREATE_RETRIES):
        try:
            instance, created = model.objects.get_or_create(defaults=defaults, **kwargs)
        except model.MultipleObjectsReturned as e:
            exception = e
            time.sleep(max(poisson_random(1), 0.5))
            continue

        if created and model.objects.filter(**kwargs).exclude(pk=instance.pk).exists():
            instance.delete()
            time.sleep(max(poisson_random(1), 0.5))
            continue
        return instance, created
    raise exception
