import datetime
import json

import django.views.decorators.http
import django.shortcuts
import django.db.models
import django.http

import mainapp.models


DEFAULT_NEWS_QUANTITY = 10


class BreakerException(Exception):
    pass


@django.views.decorators.http.require_GET
def view_index(request, sport=None, league=None, search=None, tag=None):
    try:
        if sport is not None:
            sport = mainapp.models.Sport.objects.get(clean_name=sport)
            assert sport is not None, 'sport not found'
            if league is not None:
                league = mainapp.models.League.objects.get(sport_id=sport.id, clean_name=league)
                assert league is not None, 'league not found'

        navbar_sports = mainapp.models.League.navbar_sports()
        assert navbar_sports, 'navbar sports not found'

    except BaseException:
        raise django.http.Http404()

    else:
        return django.shortcuts.render(
            request=request,
            template_name='mainapp/index.html',
            status=200,
            context={
                'sport': sport,
                'league': league,
                'search': search,
                'tag': tag,
                'navbar_sports': navbar_sports,
            }
        )


@django.views.decorators.http.require_GET
def view_news(request, title):
    try:
        navbar_sports = mainapp.models.League.navbar_sports()
        assert navbar_sports, 'navbar sports not found'

        news = mainapp.models.News.objects.get(clean_title=title)
        assert news is not None

    except BaseException:
        raise django.http.Http404()

    else:
        return django.shortcuts.render(
            request=request,
            template_name='mainapp/news.html',
            status=200,
            context={
                'navbar_sports': navbar_sports,
                'news': news
            }
        )


@django.views.decorators.http.require_GET
def api_news_list(request):
    try:
        news_filter = list()
        if request.GET.get('tag'):
            news_filter.append(django.db.models.Q(
                clean_tags__contains=[request.GET['tag']]
            ))
        elif request.GET.get('search'):
            news_filter.append(django.db.models.Q(
                haystack__contains=request.GET['search']
            ))
        else:
            if request.GET.get('sportId'):
                news_filter.append(django.db.models.Q(
                    source__sport_id=int(request.GET['sportId'])
                ))
            if request.GET.get('leagueId'):
                news_filter.append(django.db.models.Q(
                    league_id=int(request.GET['leagueId'])
                ))

        if request.GET.get('offsetId'):
            news_filter.append(django.db.models.Q(
                id__lt=int(request.GET['offsetId'])
            ))

        quantity = int(request.GET['quantity']) if request.GET.get('quantity') else DEFAULT_NEWS_QUANTITY
        news = mainapp.models.News.objects.filter(*news_filter).order_by('-pub_date')[:quantity]

    except BaseException as e:
        return django.http.JsonResponse(
            data={
                'success': False,
                'error': str(e)
            },
            status=400
        )

    else:
        return django.http.JsonResponse(
            data={
                'success': True,
                'error': None,
                'news': [ns.to_json for ns in news]
            },
            status=200
        )


@django.views.decorators.http.require_GET
def api_match_list(request):
    try:
        match_filter = list()
        if request.GET.get('sportId'):
            match_filter.append(django.db.models.Q(
                league__sport_id=int(request.GET['sportId'])
            ))
        if request.GET.get('leagueId'):
            match_filter.append(django.db.models.Q(
                league_id=int(request.GET['leagueId'])
            ))
        if request.GET.get('start'):
            match_filter.append(django.db.models.Q(
                start_date__gte=datetime.datetime.fromtimestamp(int(request.GET['start']))
            ))
        if request.GET.get('end'):
            match_filter.append(django.db.models.Q(
                start_date__lte=datetime.datetime.fromtimestamp(int(request.GET['end']))
            ))
        matches = mainapp.models.Match.objects.filter(*match_filter).order_by(
            'league__degree', 'league__id', 'start_date'
        )

    except BaseException as e:
        return django.http.JsonResponse(
            data={
                'success': False,
                'error': str(e)
            },
            status=400
        )

    else:
        return django.http.JsonResponse(
            data={
                'success': True,
                'error': None,
                'matches': [m.to_json for m in matches]
            },
            status=200
        )


@django.views.decorators.http.require_POST
def api_user_session(request):
    try:
        json_body = json.loads(request.body)

        if 'seenBuildingModal' in json_body:
            request.session['seenBuildingModal'] = json_body['seenBuildingModal']

    except BaseException as e:
        return django.http.JsonResponse(
            data={
                'success': False,
                'error': str(e)
            },
            status=400
        )

    else:
        return django.http.JsonResponse(
            data={
                'success': True,
                'error': None,
            },
            status=200
        )
