import random

from flask import Blueprint, redirect, url_for

from src.config import Configuration
from src.lib.artist import get_random_artist_keys
from src.lib.post import get_random_post_key

random_bp = Blueprint("random", __name__)


@random_bp.route("/posts/random")
def random_post():
    post = get_random_post_key(Configuration().webserver.get("table_sample_bernoulli_sample_size"))
    if post is None:
        return redirect(url_for("posts.get_posts"))

    return redirect(
        url_for(
            "post.get",
            service=post["service"],
            artist_id=post["user"],
            post_id=post["id"],
        )
    )


@random_bp.route("/artists/random")
def random_artist():
    """todo decide after random posts with redis list if its worth"""
    artist = get_random_artist()
    if artist is None:
        return redirect(url_for("artists.list"))

    # currently we don't get random discord artists but anyway...
    if artist["service"] == "discord":
        return redirect(url_for("posts.discord_server", server_id=artist["id"]))
    return redirect(url_for("artists.get", service=artist["service"], artist_id=artist["id"]))


def get_random_artist():
    artists = get_random_artist_keys(1000)
    if len(artists) == 0:
        return None
    return random.choice(artists)
