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 *
import json
from datetime import datetime, time
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync


@login_required(login_url='/profile/login/')
def get_file_from_msg_ajax(request):

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

    try:

        data = json.loads(request.body)
        msg = Message.objects.get(id=data['message_id'])

        res_Dict = {}
        for file in msg.files:
            if file['file_name'] == data['file_name']:
                res_Dict = file
                break

        return JsonResponse(res_Dict, status=200)

    except Exception as e:
        msg = f'get_file_from_msg_ajax Error = {str(e)}'
        return JsonResponse({'error': msg}, status=400)



@login_required(login_url='/profile/login/')
def show_chat_w_user_ajax(request):

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

    try:

        data = json.loads(request.body)
        Dict = get_chat_page_content_Dict(request, data['user_id'])

        tpl_name = 'blocks/profile/b_chats.html'



        html = render_to_string(tpl_name, Dict, request=request)
        return JsonResponse({'html': html}, status=200)

    except Exception as e:
        msg = f'show_chat_w_user_ajax Error = {str(e)}'
        return JsonResponse({'error': msg}, status=400)



def update_chat_ajax2(request):
    from AuthApp.models import User

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

    res_Dict = {}
    msgs = []
    Dict = {}
    context_Dict = {}

    last_message_modifiedDT = None

    required_beep = False

    try:

        data = json.loads(request.body)
        ticket = None

        tpl_name = 'blocks/profile/b_messages_container.html'


        if 'ticket_id' in data and data['ticket_id'] and data['ticket_id'] != 'null':
            ticket = MsgGroup.objects.get(id=data['ticket_id'])

        sender = User.objects.get(id=data['sender'])
        receiver = None
        if 'receiver' in data and data['receiver']:
            receiver = User.objects.get(id=data['receiver'])

        context_Dict.update({'cur_receiver': receiver})


        if not ticket:

            # получаем правую панель с получателями
            # получатели
            receivers, unread_msgs_count = get_chat_receivers_for_user(request.user, receiver)
            # собираем для сохранения в профиле
            receivers_unread_msgs_count = sorted(
                [{'id': item.id, 'unread_msgs_count': item.unread_msgs_count} for item in receivers],
                key=lambda d: d['id'])
            # забираем данные из профиля
            saved_receivers_unread_msgs_count = request.user.user_profile.get_node_by_name(
                'receivers_unread_msgs_count')
            # если данных нет или данные поменялись
            if saved_receivers_unread_msgs_count == None or receivers_unread_msgs_count != saved_receivers_unread_msgs_count:
                # записываем данные в профиль
                request.user.user_profile.add_node_to_json_data(
                    {'receivers_unread_msgs_count': receivers_unread_msgs_count}, save=True)
                # разрешаем сигнал
                required_beep = True

                # формируем правую панель
                context_Dict.update({'receivers': receivers})
                users_list_html = render_to_string(
                    'blocks/profile/b_list_of_users_messenger.html', context_Dict, request=request)
                res_Dict.update({
                    'users_list_html': users_list_html,
                    'unread_msgs_count': unread_msgs_count
                })


            if sender and receiver:
                msgs = get_msgs_for_chat_w_users(sender, receiver)
                unreaded_msgs = msgs.filter(status='sended')
                if msgs and unreaded_msgs:
                    context_Dict.update({'messages': msgs})
                    chat_html = render_to_string(tpl_name, context_Dict, request=request)
                    res_Dict.update({'chat_html': chat_html})
                    required_beep = True
                    unreaded_msgs.update(status='seen')



        res_Dict.update({
            'required_beep': required_beep,
        })
        return JsonResponse(res_Dict, status=200)

    except Exception as e:
        msg = f'update_chat_ajax2 Error = {str(e)}'
        return JsonResponse({'error': msg}, status=400)




def update_chat_ajax(request):
    from AuthApp.models import User

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

    res_Dict = {}
    msgs = []
    Dict = {}
    context_Dict = {}

    last_message_modifiedDT = None

    required_beep = False

    try:

        data = json.loads(request.body)
        ticket = None

        tpl_name = 'blocks/profile/b_messages_container.html'


        if 'ticket_id' in data and data['ticket_id'] and data['ticket_id'] != 'null':
            ticket = MsgGroup.objects.get(id=data['ticket_id'])

        if 'last_message_modifiedDT' in data:
            last_message_modifiedDT = datetime.strptime(data['last_message_modifiedDT'], '%d.%m.%Y %H:%M:%S:%f')

        sender = User.objects.get(id=data['sender'])
        receiver = None
        if 'receiver' in data and data['receiver']:
            receiver = User.objects.get(id=data['receiver'])

        context_Dict.update({'cur_receiver': receiver})

        if ticket:

            context_Dict.update({
                'ticket': ticket,
            })

            msgs = get_messages_for_ticket(ticket)
            context_Dict.update({'messages': msgs})
            context_Dict = get_ticketsDict_for_staff(request.user)

            tickets_list_html = render_to_string(
                'blocks/profile/b_list_of_tickets_support_chat.html', context_Dict, request=request)
            res_Dict.update({
                'tickets_list_html': tickets_list_html,
                'msgs_count': len(msgs)
            })
        else:

            # получаем правую панель с получателями
            receivers, unread_msgs_count = get_chat_receivers_for_user(request.user, receiver)
            receivers_unread_msgs_count = sorted([{'id':item.id, 'unread_msgs_count': item.unread_msgs_count} for item in receivers], key=lambda d: d['id'])
            saved_receivers_unread_msgs_count = request.user.user_profile.get_node_by_name('receivers_unread_msgs_count')
            if saved_receivers_unread_msgs_count == None or receivers_unread_msgs_count != saved_receivers_unread_msgs_count:
                request.user.user_profile.add_node_to_json_data(
                    {'receivers_unread_msgs_count': receivers_unread_msgs_count}, save=True)
                # if unread_msgs_count:
                required_beep = True

                context_Dict.update({'receivers': receivers})
                users_list_html = render_to_string(
                    'blocks/profile/b_list_of_users_messenger.html', context_Dict, request=request)
                res_Dict.update({
                    'users_list_html': users_list_html,
                    'unread_msgs_count': unread_msgs_count
                })

            # если есть получатель - получаем сообщения чата
            if receiver:
                msgs = get_msgs_for_chat_w_users(sender, receiver)
                unreaded_msgs = msgs.filter(status='sended')
                if msgs and unreaded_msgs:
                    context_Dict.update({'messages': msgs})
                    chat_html = render_to_string(tpl_name, context_Dict, request=request)
                    res_Dict.update({'chat_html': chat_html})
                    required_beep = True
                    unreaded_msgs.update(status='seen')

            # if not msgs or (request.user != msgs[0].receiver) or (not msgs and not last_message_modifiedDT) or (msgs and last_message_modifiedDT and msgs[0].modifiedDT <= last_message_modifiedDT):
            #     Dict.update({
            #         'required_beep': False
            #     })
            #     return JsonResponse(Dict, status=200)



        res_Dict.update({
            'required_beep': required_beep,
        })
        return JsonResponse(res_Dict, status=200)

    except Exception as e:
        msg = f'update_chat_ajax Error = {str(e)}'
        return JsonResponse({'error': msg}, status=400)


# @login_required(login_url='/profile/login/')
# def send_msg_ajax(request):
#     from AuthApp.models import User
#
#     if request.method != 'POST':
#         raise Http404
#
#     res_Dict = {}
#     msg = None
#
#     try:
#
#         data = json.loads(request.body)
#         ticket = None
#
#         tpl_name = 'blocks/profile/b_messages_container.html'
#
#         if data['text']:
#
#
#             if 'ticket_id' in data:
#                 ticket = MsgGroup.objects.get(id=data['ticket_id'])
#
#             sender = User.objects.get(id=data['sender'])
#             receiver = User.objects.get(id=data['receiver'])
#
#             msg_create_kwargs = {}
#
#             # если только что манагер присоединился к тикету
#             if ticket:
#                 if not ticket.manager:
#                     if sender.is_staff:
#                         ticket.manager = sender
#                     else:
#                         ticket.manager = receiver
#
#                     ticket.save()
#
#                     kwargs = {
#                         'sender': ticket.owner,
#                         'receiver': ticket.manager,
#                         'text': ticket.text,
#                     }
#
#                     kwargs.update({'group': ticket})
#
#                     msg = Message.objects.create(**kwargs)
#                     Message.objects.filter(id=msg.id).update(modifiedDT=ticket.createDT, createDT=ticket.createDT)
#
#                 # if
#
#                 res_Dict.update({
#                     'ticket': ticket,
#                     # 'cur_receiver': receiver,
#                     # 'messages': get_messages_for_ticket(ticket),
#                     # 'text': data['text'],
#                     # 'modifiedDT': msg.modifiedDT
#                 })
#
#                 msg_create_kwargs.update({
#                     'group': ticket,
#                 })
#
#                 res_Dict.update(get_ticketsDict_for_staff(request.user))
#
#
#             # if not msg:
#             msg_create_kwargs.update({
#                 'sender': sender,
#                 'receiver': receiver,
#                 'text': data['text']
#             })
#
#             session_data = {
#                 'for_save_to_session':{
#                     'user_alerts':{
#                         'new_message': True
#                     }
#                 }
#             }
#
#             receiver.user_profile.add_node_to_json_data(session_data, save=True)
#
#             msg = Message.objects.create(**msg_create_kwargs)
#
#             if ticket:
#                 msgs = get_messages_for_ticket(ticket)
#             else:
#                 msgs = get_msgs_for_chat_w_users(sender, receiver)
#
#             receivers, unread_msgs_count = get_chat_receivers_for_user(request.user)
#
#
#             res_Dict.update({
#                 'messages': msgs,
#                 'cur_receiver': receiver,
#                 'receivers': receivers,
#                 'text': data['text'],
#                 'modifiedDT': msgs[0].modifiedDT
#             })
#
#
#         html = render_to_string(tpl_name, res_Dict, request=request)
#         return JsonResponse({'html': html}, status=200)
#
#     except Exception as e:
#         msg = f'send_msg_ajax Error = {str(e)}'
#         return JsonResponse({'error': msg}, status=400)




@login_required(login_url='/profile/login/')
def support_show_chat_by_ticket_ajax(request):

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

    try:

        data = json.loads(request.body)

        ticket = MsgGroup.objects.get(id=data['ticket_id'])

        msgs = get_messages_for_ticket(ticket)

        new_msg_allow = False
        cur_receiver = None
        if request.user.is_staff:
            cur_receiver = ticket.owner
            new_msg_allow = True
        else:
            if ticket.manager:
                cur_receiver = ticket.manager
            # if len(msgs) > 1:
                new_msg_allow = True

        seen_msgs = msgs.filter(receiver=request.user, status='sended')
        if seen_msgs:
            seen_msgs.update(status='seen')
            msgs = get_messages_for_ticket(ticket)

        Dict = {
            'ticket': ticket,
            'messages': msgs,
            'cur_receiver': cur_receiver,
            'new_msg_allow': new_msg_allow,
            'staff': request.user.is_staff,
            'mobile': data['mobile']
        }
        Dict.update(get_ticketsDict_for_staff(request.user))

        tpl_name = 'blocks/profile/b_support_chat.html'

        html = render_to_string(tpl_name, Dict, request=request)
        return JsonResponse({'html': html}, status=200)

    except Exception as e:
        msg = f'support_show_chat_by_ticket_ajax Error = {str(e)}'
        return JsonResponse({'error': msg}, status=400)


@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()
    }
    tpl_name = 'blocks/profile/b_create_ticket.html'

    html = render_to_string(tpl_name, 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)

        ticket = form.save(commit=False)
        ticket.owner = request.user
        ticket.enable = True
        ticket.save()

        from .websocket_views import send_to_support_managers_list_tickets_wo_manager
        send_to_support_managers_list_tickets_wo_manager(ticket, required_beep=True)
        # # рассылаем всем менеджерам сообщение
        #
        # Dict = {
        #     'ticket': ticket,
        #     'tickets_wo_manager': get_tickets_wo_manager()
        # }
        # tickets_wo_manager_html = render_to_string('widgets/w_tickets_wo_manager.html', Dict, request=request)
        #
        # group_name = 'support_managers'
        # Dict = {
        #     'type': 'update_chat',
        #     'tickets_wo_manager_html': tickets_wo_manager_html,
        #     'required_beep': True,
        #     'group_name': group_name,
        # }
        # channel_layer = get_channel_layer()
        # async_to_sync(channel_layer.group_send)(
        #     group_name,
        #     Dict
        # )
        #
        #
        # # ---------------------

        msgs_for_ticket = get_messages_for_ticket(ticket)
        Dict = {
            'ticket': ticket,
            'messages': msgs_for_ticket
        }

        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)



def sendDeployments(owner, armies):
    type = "renderDeployments"
    message = owner + " has " + str(armies) + " to deploy"
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'render_updates_group',
        {'type': 'render', 'message': message}
    )