import random
from emails.models import Emails
from gameruns.models import GameRuns, EmailGameRuns
from settings.models import Settings


def set_random_emails(gamerun_id: int):
    """
    Gets random legitimate and phishing emails
    and sets them to the given gamerun, without repetition

    :param gamerun_id: ID of gamerun
    :returns: None
    """

    # from settings get how many emails should be in gamerun
    number_of_emails = Settings.objects.get(key__exact="number_of_emails").value
    # from settings get ratio of phishing emails in gamerun
    perc_of_phishing = Settings.objects.get(key__exact="phishing_emails").value
    #calculate number of phishing emails in gamerun
    number_of_phishing_emails = int(
        round(
            number_of_emails * (perc_of_phishing / 100), 0
        ))
    number_of_legit_emails = number_of_emails - number_of_phishing_emails

    # email with type id 1 is legitimate, type id > 1 means phishing
    phishing_emails = list(Emails.objects.filter(type__id__gt=1))  # phishing emails
    legitimate_emails = list(Emails.objects.filter(type__id=1))  # legitimate emails

    random_phishing_emails = random.sample(phishing_emails, number_of_phishing_emails)
    random_legitimate_emails = random.sample(legitimate_emails, number_of_legit_emails)

    GameRuns.objects.get(id=gamerun_id).emails.set(random_phishing_emails + random_legitimate_emails)


