import datetime
import json
import operator
from functools import reduce
from pathlib import Path

from django.conf import settings
from django.core.cache import cache
from django.db import models, transaction
from django.utils.functional import cached_property
from django.utils.html import strip_tags
from django_hosts.resolvers import reverse
from django.utils.text import unescape_entities

from releases.models import Release

from . import utils


class DocumentReleaseManager(models.Manager):

    def current(self, lang='en'):
        current = self.get(is_default=True)
        if lang != 'en':
            try:
                return self.get(lang=lang, release=current.release)
            except DocumentRelease.DoesNotExist:
                pass
        return current

    def current_version(self):
        current_version = cache.get(DocumentRelease.DEFAULT_CACHE_KEY)
        if not current_version:
            try:
                current_version = self.current().version
            except DocumentRelease.DoesNotExist:
                current_version = 'dev'
            cache.set(
                DocumentRelease.DEFAULT_CACHE_KEY,
                current_version,
                settings.CACHE_MIDDLEWARE_SECONDS,
            )
        return current_version

    def get_by_version_and_lang(self, version, lang):
        return self.get(lang=lang, **{'release__isnull': True} if version == 'dev' else {'release': version})


class DocumentRelease(models.Model):
    """
    A "release" of documentation -- i.e. English for v1.2.
    """