import json

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 .forms import *
from .funcs import *


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

    try:

        data = json.loads(request.body)
        if not 'route_id' in data:
            msg = f'Недостаточно данных'
            return JsonResponse({'errors': msg})

        route = Route.objects.filter(id=data['route_id']).delete()

        routes_Dict = get_routes_Dict(request.user)
        if 'errors' in routes_Dict:
            return JsonResponse(routes_Dict, status=400)

        html = render_to_string('blocks/profile/b_my_routes.html', routes_Dict, request=request)

        res_Dict = {
            'html': html
        }

        return JsonResponse(res_Dict)

    except Exception as e:
        # form.errors.append({'__all__': f'Ошибка: {str(e)}'})
        msg = f'Ошибка del_route_ajax = {str(e)}'
        print(msg)
        return JsonResponse({'errors': msg})



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

    data = json.loads(request.body)

    Dict = {}

    try:

        if not 'route_id' in data:
            msg = f'Недостаточно данных'
            return JsonResponse({'errors': msg})

        route = Route.objects.get(id=data['route_id'])

        form = RouteForm(instance=route)
        route_address_points_Dict = route.get_address_points()
        form.initial.update({
            'from_address_point_txt': route_address_points_Dict['from_address_point_txt'],
            'to_address_point_txt': route_address_points_Dict['to_address_point_txt'],
        })


        Dict = {
            'form': form,
            'route': route
        }

    except Exception as e:
        # form.errors.append({'__all__': f'Ошибка: {str(e)}'})
        msg = f'Ошибка edit_route = {str(e)}'
        print(msg)
        return JsonResponse({'errors': msg})

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






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

    # form = RouteForm()
    # Dict = {
    #     'form': form
    # }
    try:

        errors_off = True

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

        html = get_profile_new_route_page_html(request, data)


    except Exception as e:
        # form.errors.append({'__all__': f'Ошибка: {str(e)}'})
        msg = f'new_route_view_ajax Error = {str(e)}'
        print(msg)
        html = msg


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


def find_routes_ajax(request):


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

    try:


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

        if not 'owner_type' in data:
            data['owner_type'] = 'mover'
        routes_Dict = get_routes_Dict(data=data)
        if 'errors' in routes_Dict:
            return JsonResponse(routes_Dict, status=400)

        if routes_Dict['routes']:
            html = render_to_string('blocks/b_search_routes.html', routes_Dict, request=request)
        else:
            html = render_to_string('templates_js_translate/not_found_find_routes.html', routes_Dict, request=request)

        res_Dict = {
            'html': html,
            'last_block': routes_Dict['last_block'],
            'next_page_els_count': routes_Dict['next_page_els_count'],
            # 'form': RouteForm(initial=data)
        }

        return JsonResponse(res_Dict)

    except Exception as e:

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


def get_my_routes_ajax(request):


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

    try:
        routes_Dict = get_routes_Dict(request.user)
        if 'errors' in routes_Dict:
            return JsonResponse(routes_Dict, status=400)


        html = render_to_string('blocks/profile/b_my_routes.html', routes_Dict, request=request)

        res_Dict = {
            'html': html
        }

        return JsonResponse(res_Dict)

    except Exception as e:

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



def create_or_change_route_ajax(request, route_id=None):
    from ReferenceDataApp.models import Airport, City

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

    Dict = {}

    try:

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

        route = None
        if route_id:
            route = Route.objects.get(id=route_id)

        if route:
            form = RouteForm(data, instance=route)
            Dict.update({'route': route})
        else:
            form = RouteForm(data)

        if not form.is_valid():
            form.initial = form.cleaned_data
            Dict.update({'form': form})

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

        obj = form.save(commit=False)
        if 'owner_type' in data and data['owner_type']:
            obj.owner_type = data['owner_type']

        if obj.from_address_point:
            obj.from_city = get_city_by_type_transport_and_address_point(obj.type_transport, obj.from_address_point)

        if obj.to_address_point:
            obj.to_city = get_city_by_type_transport_and_address_point(obj.type_transport, obj.to_address_point)

        obj.owner = request.user
        obj.save()

        route_id = obj.id

        routes_Dict = get_routes_Dict(request.user)

        if 'errors' in routes_Dict:
            form.errors.update(routes_Dict['errors'])
            Dict.update({'form': form})
            html = render_to_string('blocks/profile/b_new_route.html', Dict, request=request)
            return JsonResponse({'html': html}, status=400)

        html = render_to_string('blocks/profile/b_my_routes.html', routes_Dict, request=request)

        res_Dict = {
            'html': html,
            'route_id': route_id
        }

        return JsonResponse(res_Dict)

    except Exception as e:

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