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
from django.core.validators import validate_email


# @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)



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

    try:

        data = request.POST
        if not data and request.body:
            data = request.body

        from GeneralApp.funcs_options import get_options_by_opt_types, get_mail_send_options
        sets = get_options_by_opt_types(['domain', 'project_name'], only_vals=True)

        request_type = None
        subject = _('Получен запрос')
        if 'form_name' in data:
            if data['form_name'] == 'msg_from_advertisement':
                subject = _('Получен запрос на рекламу')
                request_type = _('запрос на рекламу')
            if data['form_name'] == 'msg_from_partners':
                subject = _('Получен запрос на подключение к партнерской сети')
                request_type = _('запрос на партнерство')
            if data['form_name'] == 'msg_from_customer_service':
                subject = _('Получен запрос в службу техподдержки')
                request_type = _('запрос в техподдержку')
            if data['form_name'] == 'msg_from_contacts':
                subject = _('Получен запрос со страницы контактов')
                request_type = _('запрос со страницы контактов')
            if data['form_name'] == 'msg_from_about_service':
                subject = _('Получен запрос со страницы О сервисе')
                request_type = _('запрос со страницы о сервисе')
            if data['form_name'] == 'msg_from_footer':
                subject = _('Получен запрос на рассылку')
                request_type = _('запрос на рассылку')

        request_type_str = ''
        name_str = ''
        phone_str = ''
        email_str = ''
        msg_str = ''
        form_type = 'one_field'
        errors = {}

        for name, val in data.items():
            if not val:
                errors.update({name: _('Обязательное поле')})

            if name == 'form_name':
                request_type_str = f'<b>{_("Тип запроса")}:</b> {request_type}<br>'

            if name == 'name':
                name_str = f'<b>{_("Имя")}:</b> {data["name"]}<br>'
                if form_type == 'one_field':
                    form_type = 'two_fields'

            if name =='phone':
                from BaseModels.validators.form_field_validators import get_phone_valid_error
                error = get_phone_valid_error(data["phone"])
                if error:
                    errors.update({name: _(error)})
                phone_str = f'<b>{_("Телефон")}:</b> {data["phone"]}<br>'

            if name =='email':
                try:
                    error = validate_email(data["email"])
                except ValidationError as e:
                    error = e.message
                if error:
                    errors.update({name: _(error)})
                email_str = f'<b>{_("email")}:</b> {data["email"]}<br>'

            if name =='text_msg':
                msg_str = (f'<b>{_("Сообщение")}:</b><br>'
                           f'<div style="margin-left: 40px; line-height: 20px;">{data["text_msg"]}</div><br>')
                form_type = 'full'

        if errors:
            Dict = {
                'form': data.dict()
            }
            Dict['form'].update({
                'errors': errors
            })

            tpl = 'forms/f_one_field_form.html'
            if form_type == 'full':
                tpl = 'forms/f_feedback_form.html'
            elif form_type == 'two_fields':
                tpl = 'forms/f_commercial_offer.html'

            html = render_to_string(tpl, Dict, request)
            return JsonResponse({'html': html}, status=400)

        Dict = {
            'logo': f'{sets["domain"]}/static/img/svg/LogoMobile.svg',
            'project_name': sets['project_name'],
            'message_title': subject,
            'message_text': f'<p><b>{_("ДАННЫЕ ЗАПРОСА")}</b></p>'
                            f'<p style="padding-left: 20px; line-height: 30px;">'
                            f'{request_type_str}'
                            f'{name_str}'
                            f'{phone_str}'
                            f'{email_str}'
                            f'{msg_str}'
                            f'</p>'
        }

        html = render_to_string('mail/m_request_offer.html', Dict, request)
        from BaseModels.mailSender import admin_send_mail_by_SMTPlib
        mail_sets = get_mail_send_options()
        to = [mail_sets['sender_email'], 'web@syncsystems.net']
        res = admin_send_mail_by_SMTPlib(
            mail_sets,
            subject=subject,
            from_email=mail_sets['sender_email'], to=to,
            html_content=html
        )

        html = render_to_string('widgets/w_msg_send_success.html', Dict, request)

        return JsonResponse({
            'status': 'sended',
            'html': html
        })
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'html': str(e)
        }, status=400)


@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
    kwargs = {
        'not_required_password': True,
        'not_required_agreement': True,
        'not_required_email': True,
        'create_new_account': False,
    }
    form = RegistrationForm(data, **kwargs)
    if not form.is_valid():
        form.initial = data
        Dict = {'profileForm': form}

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

    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__': _("неверный логин и\или пароль")
                }
            }
            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, backend='django.contrib.auth.backends.ModelBackend')

        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)

