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 subscribe_ajax(request):
    if request.method != 'POST':
        raise Http404

    Dict = {
    }

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

@login_required(login_url='/profile/login/')
def new_msg_to_user_ajax(request):
    if request.method != 'POST':
        raise Http404

    Dict = {
    }

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

@login_required(login_url='/profile/login/')
def support_tickets_ajax(request):
    if request.method != 'POST':
        raise Http404

    Dict = {
    }

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



@login_required(login_url='/profile/login/')
def change_profile_ajax(request):
    if request.method != 'POST':
        raise Http404

    Dict = {
    }

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


@login_required(login_url='/profile/login/')
def my_routes_ajax(request):
    if request.method != 'POST':
        raise Http404

    Dict = {
    }

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





def login_ajax(request):
    if request.method != 'POST':
        raise Http404

    try:

        data = request.POST

        from .forms import LoginForm
        form = LoginForm(data)
        if not form.is_valid():
            Dict = {'form': form}
            html = render_to_string('forms/f_login.html', Dict, request=request)
            return JsonResponse({'html': html}, status=400)

        from django.contrib.auth import authenticate
        user = authenticate(username=form.data['username'], password=form.data['password'])
        if user is not None:
            auth.login(request, user)
        else:
            errors_Dict = {
                'errors': {
                    'all__': f'неверный логин и\или пароль'
                }
            }
            Dict = {'form': errors_Dict}
            html = render_to_string('forms/f_login.html', Dict, request=request)
            return JsonResponse({'html': html}, status=400)


        res_Dict = {
            'redirect_url': reverse('user_profile')
        }

        return JsonResponse(res_Dict)

    except Exception as e:

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


def registration_ajax(request):
    if request.method != 'POST':
        raise Http404

    try:

        data = request.POST

        from .forms import RegistrationForm
        form = RegistrationForm(data)
        if not form.is_valid():
            Dict = {'form': form}
            html = render_to_string('forms/f_registration.html', Dict, request=request)
            return JsonResponse({'html': html}, status=400)

        users = User.objects.filter(email=form.data['email'])
        if users:
            form.errors['email'] = 'Пользователь с указанным email уже существует'
            Dict = {'form': form}
            html = render_to_string('forms/f_registration.html', Dict, request=request)
            return JsonResponse({'html': html}, status=400)

        user = User.objects.create_user(username=form.data['email'], email=form.data['email'], password=form.data['password'])
        # user = auth.authenticate(username=new_user_Dict['name'], password=new_user_Dict['pass'])
        if user:
            auth.login(request, user)

        user.last_name = form.data['lastname']
        user.first_name = form.data['firstname']
        user.save()
        user.user_profile.phone = form.data['tel']
        user.user_profile.save()

        res_Dict = {
            'redirect_url': reverse('user_profile')
        }

        return JsonResponse(res_Dict)

    except Exception as e:

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

