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.core.exceptions import ValidationError
import json
from django.core.files import File
import base64


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

    from ChatServiceApp.funcs import get_chat_receivers_for_user, get_msgs_for_chat_w_users

    receivers, unread_msgs_count = get_chat_receivers_for_user(request.user)

    cur_chat_msgs = None

    # try:
    #     cur_receiver = User.objects.get(id=user_id)
    #     if not cur_receiver in receivers:
    #         receivers.insert(0, cur_receiver)
    #     cur_chat_msgs = get_msgs_for_chat_w_users(request.user, cur_receiver)
    # except User.DoesNotExist:
    #     cur_receiver = None

    Dict = {
        'page': 'chat',
        # 'cur_receiver': cur_receiver,
        'receivers': receivers,
        # 'messages': cur_chat_msgs
    }

    html = render_to_string('blocks/profile/b_chats.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

    html = get_profile_support_page_content_html(request)

    return JsonResponse({'html': html}, status=200)


@login_required(login_url='/profile/login/')
def change_avatar_confirm_ajax(request):
    from django.core.files.base import ContentFile

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

    try:

        file_data = json.loads(request.body)
        head, content = file_data['file'].split(',')
        content = base64.b64decode(content)
        file = ContentFile(content)
        request.user.user_profile.avatar.save(file_data['file_name'], file)
        request.user.user_profile.save(update_fields=['avatar'])

    except Exception as e:
        msg = f'change_avatar_confirm_ajax Error = {str(e)}'
        print(msg)
        JsonResponse({'error': msg})

    return JsonResponse({'url': request.user.user_profile.avatar.url})


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

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

    from .forms import RegistrationForm
    form = RegistrationForm(data)

    data_for_save = {}
    users = User.objects.filter(id=request.user.id)
    if 'firstname' in data:
        data_for_save.update({'first_name': data['firstname']})
    if 'lastname' in data:
        data_for_save.update({'last_name': data['lastname']})
    if 'email' in data:
        data_for_save.update({'email': data['email']})
        data_for_save.update({'username': data['email']})

    if data_for_save:
        users.update(**data_for_save)

    data_for_save = {}

    password = None
    confirm_password = None
    if 'password' in data:
        password = data['password']
    if 'confirm_password' in data:
        confirm_password = data['confirm_password']
    if password and confirm_password:
        if password != confirm_password:
            errors = {
                'password': 'Не совпадают пароли',
                'confirm_password': 'Не совпадают пароли',
            }
            raise ValidationError(errors)

        request.user.set_password(password)
        request.user.save()


    data_for_save = {}
    user_profiles = UserProfile.objects.filter(user__in=users)
    if 'country' in data:
        data_for_save.update({'country': data['country']})
    if 'city' in data:
        data_for_save.update({'city': data['city']})
    if 'tel' in data:
        data_for_save.update({'phone': data['tel']})

    if data_for_save:
        user_profiles.update(**data_for_save)

    html = get_profile_change_page_content_html(request)
    return JsonResponse({'html': html}, status=200)


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

    try:

        from .funcs import get_dashboard_page_content_html
        html = get_dashboard_page_content_html(request)

    except Exception as e:
        msg = f'dashboard_ajax Error = {str(e)}'
        print(msg)
        html = msg

    return JsonResponse({'html': html}, status=200)


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


    html = get_profile_change_page_content_html(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('profile_page', args=['dashboard'])
        }

        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('profile_page', args=['dashboard'])
        }

        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)

