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 django.db.models import Q
import json
from GeneralApp.funcs import get_inter_http_respose

def get_address_point_ajax(request):
    from .funcs import search_cities_in_db, search_airports_in_db

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

    try:

        data = json.loads(request.body)

        if not 'search_str' in data or not 'type_transport' in data or not 'ctrl_name' in data:
            errors_Dict = {
                'errors': {
                    'all__': f'ошибка в запросе = недостаточно данных'
                }
            }
            return JsonResponse(errors_Dict, status=400)

        if len(data['search_str'].strip()) < 3:
            res_data = []
        else:
            if data['type_transport'] == 'avia':
                res_data = search_airports_in_db(data['search_str'])
            else:
                res_data = search_cities_in_db(data['search_str'])

        res_data_str_list = []
        i = 0
        html = ''
        for item in res_data:
            item['index'] = i
            item['ctrl_name'] = data['ctrl_name']
            if 'iata_code' in item:
                item['airport_fullname'] = f'<b>{item["iata_code"]}</b> - {item["name"]}'
                item['fullname'] = f'{item["iata_code"]} - {item["name"]}'
                item['city_name'] = item['city__name']
                item['country_name'] = item['city__country__name']
            else:
                item['city_name'] = item['name']
                item['country_name'] = item['country__name']
                item['fullname'] = f'{item["country_name"]} / {item["city_name"]}'
            html = f"{html}{render_to_string('widgets/w_ac_input_address_point.html', item)}"
            i += 1


        res_Dict = {
            'res_search_list': html
        }

        return JsonResponse(res_Dict)

    except Exception as e:

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