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 get_routes_for_user


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

        if 'from_address_point' in data:
            del data['from_address_point']
        if 'from_address_point_txt' in data:
            del data['from_address_point_txt']

        if 'to_address_point' in data:
            del data['to_address_point']
        if 'to_address_point_txt' in data:
            del data['to_address_point_txt']

        if 'type_transport' in data:
            if data['type_transport'] == 'avia':
                transfer_location_choices = (
                    ('airport', _('В аэропорту')),
                    ('city', _('По городу')),
                    ('other', _('По договоренности'))
                )

                cargo_type_choices = (
                    ('passenger', _('Пассажир')),
                    ('cargo', _('Груз')),
                    ('parcel', _('Бандероль')),
                    ('package', _('Посылка')),
                    ('letter', _('Письмо\Документ'))
                )


            else:
                transfer_location_choices = (
                    ('city', _('По городу')),
                    ('other', _('По договоренности'))
                )

                cargo_type_choices = (
                    ('cargo', _('Груз')),
                    ('parcel', _('Бандероль')),
                    ('package', _('Посылка')),
                    ('letter', _('Письмо\Документ'))
                )

            form = RouteForm(data)
            if not form.is_valid():
                pass
            form = RouteForm(initial=form.cleaned_data)

            form.fields['from_place'].choices = transfer_location_choices
            form.fields['to_place'].choices = transfer_location_choices
            form.fields['cargo_type'].choices = cargo_type_choices

            form.base_fields['from_place'].choices = transfer_location_choices
            form.base_fields['to_place'].choices = transfer_location_choices
            form.base_fields['cargo_type'].choices = cargo_type_choices

            # form = CreateRouteForm(initial=data)

            # if not form.is_valid():
            #     pass

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

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

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


def get_routes_ajax(request):


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

    try:
        routes_Dict = get_routes_for_user(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):

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

    try:

        data = request.POST

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

        if route:
            form = RouteForm(data, instance=route)
        else:
            form = RouteForm(data)

        if not form.is_valid():
            form.initial = form.cleaned_data
            Dict = {'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)
        obj.owner = request.user
        obj.save()

        routes_Dict = get_routes_for_user(request.user)

        if 'errors' in routes_Dict:
            form.errors.update(routes_Dict['errors'])
            Dict = {'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
        }

        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_new_route.html', Dict, request=request)
        return JsonResponse({'html': html}, status=400)