import os
from collections import deque
from random import randint

from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from django.utils.text import slugify

from authentications.decorators import authenticated_user
from .models import Album
from .utils import create_thumbs, get_folder_list, get_image_list


def index(request):
    if request.user.is_authenticated:
        albums = deque(Album.objects.all().order_by("-event_date"))
    else:
        # show only PUBLIC albums.
        albums = deque(
            Album.objects.filter(status=Album.PUBLIC).order_by("-event_date")
        )

    for album in list(albums):
        img_list = get_image_list(album.folder_name)
        if img_list:
            if album.thumbnail:
                for img in img_list:
                    if album.thumbnail in img["title"]:
                        album.thumbnail = img["thumb_url"]
                        break
                else:
                    value = randint(0, len(img_list) - 1)
                    album.thumbnail = img_list[value]["thumb_url"]
            else:
                value = randint(0, len(img_list) - 1)
                album.thumbnail = img_list[value]["thumb_url"]
        else:
            # empty album is set to DRAFT.
            album.status = Album.DRAFT

    if request.user.is_authenticated:
        for folder in get_folder_list():
            if not Album.objects.filter(folder_name=folder):
                album = Album(
                    title=folder,
                    slug=slugify(folder),
                    folder_name=folder,
                    event_date=None,
                )

                img_list = get_image_list(album.folder_name)
                if img_list:
                    value = randint(0, len(img_list) - 1)
                    album.thumbnail = img_list[value]["thumb_url"]
                    albums.append(album)

    context = {
        "albums": albums,
    }

    return render(request, "gallery/index.html", context)


def show_album(request, slug):
    album = Album.objects.filter(slug=slug).first()
    if not album:
        for folder in get_folder_list():
            if slug in slugify(folder):
                album = Album(
                    title=folder,
                    slug=slugify(folder),
                    folder_name=folder,
                    event_date=None,
                )
                break
        else:
            raise Http404("wrong album slug")

    img_list = get_image_list(album.folder_name)
    create_thumbs(album.folder_name)

    context = {
        "album": album,
        "images": img_list,
    }

    return render(request, "gallery/album.html", context)


@authenticated_user
def show_draft_album(request, slug):
    return show_album(request, slug)
