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






@login_required(login_url='/profile/login/')
def support_create_ticket_form_ajax(request):
    from ChatServiceApp.forms import TicketForm

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

    Dict = {
        'form': TicketForm()
    }

    html = render_to_string('blocks/profile/b_create_ticket.html', Dict, request=request)
    return JsonResponse({'html': html}, status=200)


@login_required(login_url='/profile/login/')
def create_ticket_ajax(request):
    from ChatServiceApp.forms import TicketForm

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

    try:

        data = request.POST

        form = TicketForm(data)
        if not form.is_valid():
            form.initial = form.cleaned_data
            Dict = {'form': form}
            html = render_to_string('blocks/profile/b_create_ticket.html', Dict, request=request)
            return JsonResponse({'html': html}, status=400)

        obj = form.save(commit=False)
        obj.owner = request.user
        obj.save()

        Dict = {
            'ticket': obj
        }


        html = render_to_string('blocks/profile/b_support_chat.html', Dict, request=request)

        res_Dict = {
            'html': html
        }

        return JsonResponse(res_Dict)

    except Exception as e:

        errors_Dict = {
            'errors': {
                'all__': f'ошибка в запросе = {str(e)}'
            }
        }
        Dict = {'form': errors_Dict}
        html = render_to_string('blocks/profile/b_create_ticket.html', Dict, request=request)
        return JsonResponse({'html': html}, status=400)

