import json

from django.shortcuts import render

from uuid import uuid1

from .forms import FeedbackForm
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 BaseModels.mailSender import admin_send_mail_by_SMTPlib
from .funcs_options import get_mail_send_options, get_first_option_value_by_opt_type, get_options_by_opt_types


def send_feedback_form_ajax(request):

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

    try:



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

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

        feedback_form = FeedbackForm(data=data)

        if not feedback_form.is_valid():
            feedback_form.initial = data
            Dict = {'feedback_form': feedback_form}
            left_html = render_to_string('widgets/elements_form_feedback.html', Dict, request=request)
            right_html = render_to_string('widgets/w_checkbox_f_feedback.html', Dict, request=request)
            err_Dict = {
                'left_form_html': left_html,
                'right_form_html': right_html
            }
            return JsonResponse(err_Dict, status=400)

        subject = f'Сообщение из формы "{data["form_name"]}"'

        sets = get_options_by_opt_types(['domain', 'project_name'], only_vals=True)

        message_text = (f'<p><b>{_("ДАННЫЕ ЗАПРОСА")}</b></p>'
                        f'<p style="padding-left: 20px; line-height: 30px;">')
        for f_name, f_val in data.items():
            message_text += f'<b>{f_name}:</b> {f_val}<br>'

        message_text += f'</p>'

        Dict = {
            'logo': f'{request.scheme}://{sets["domain"]}{get_logo_url()}',
            'project_name': sets['project_name'],
            'message_title': subject,
            'message_text': message_text
        }


        html = render_to_string('mail/mt_simple_letter.html', Dict, request=request)


        to = [get_first_option_value_by_opt_type('corp_email'), 'web@syncsystems.net']

        mail_sets = get_mail_send_options()
        msg = admin_send_mail_by_SMTPlib(
            mail_sets, subject=subject,
            from_email=mail_sets['sender_email'], to=to, html_content=html,
        )
        print(msg)


        Dict = {
        }

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

        res_Dict = {
            'html': html,
        }

        return JsonResponse(res_Dict)

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


