import json

from django.shortcuts import render

from uuid import uuid1
from .models import *
from django.contrib import auth
from django.http import HttpResponse, Http404, JsonResponse
from django.template import loader, RequestContext
from django.contrib.auth.decorators import login_required
from BaseModels.mailSender import techSendMail
from django.utils.translation import gettext as _
from datetime import datetime
from django.template.loader import render_to_string
from django.urls import reverse
from .funcs import *
from django.utils.translation import activate, get_language_info
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def get_content_for_section_ajax(request):

    if request.method != 'POST':
        raise Http404

    try:

        data = request.POST.dict()
        if not data and request.body:
            data = json.loads(request.body)

        if 'lang' in data:
            activate(data['lang'])

        if 'screen_width' in data and data['screen_width']:
            request.session['screen_width'] = data['screen_width']

        if not 'section_url' in data or not data['section_url']:
            msg = _("Не найден section_url в data")
            err_Dict = {
                'error': msg
            }
            return JsonResponse(err_Dict, status=400)

        section = Section.objects.get(url=data['section_url'])



        # one_list_childs = {
        #     'name' : 'вгд'
        # }
        # list_childs = [one_list_childs]
        # one_list_el = {
        #     'name':'абв',
        #     'childs': list_childs
        # }
        # els_footer_list = [one_list_el]
        #
        show_slider = True
        if '/section/' in request.META.get('HTTP_REFERER'):
            show_slider = False

        Dict = {
            'page': section,
            'show_slider': show_slider,
            # 'sections': get_sections(),
            # 'services': services,
        }


        from .funcs import get_section_views_Dict
        Dict.update(get_section_views_Dict(section))

        from GeneralApp.funcs import get_inter_Dict
        Dict.update(get_inter_Dict(request.user, Dict))

        html = render_to_string('pages/content/c_section_content.html', Dict, request=request)

        res_Dict = {
            'html': html,
        }
        if section:
            res_Dict.update({'title': section.get_title()})

        return JsonResponse(res_Dict)

    except Exception as e:
        msg = f' get_content_for_section_ajax ошибка в запросе = {str(e)}'
        errors_Dict = {
            'errors':  msg
        }
        return JsonResponse(errors_Dict, status=400)
