from .models import *
from .forms import *
from django.utils.translation import gettext as _
from django.template.loader import render_to_string
from datetime import datetime

def get_profile_new_route_page_html(request, data):

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

        errors_off = True

        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 html


def get_country_n_city_str_by_type_transport_and_address_point(type_transport, address_point):
    city = get_city_by_type_transport_and_address_point(type_transport, address_point)
    return city.get_country_n_city_str()


def get_city_by_type_transport_and_address_point(type_transport, address_point):
    from ReferenceDataApp.models import Airport, City

    try:
        if type_transport == 'avia':
            return Airport.objects.get(id=address_point).city
        else:
            return City.objects.get(id=address_point)
    except Exception as e:
        msg = f'get_city_by_type_transport_and_address_point Error = {str(e)}, type_transport = {type_transport}, address_point = {address_point}'
        print(msg)
        return None


def get_profile_my_routes_page_content_html(request):
    routes_Dict = get_routes_Dict(request.user)
    if 'errors' in routes_Dict:
        msg = f'get_my_routes_page_content_html errors = {str(routes_Dict)}'
        print(msg)
        return msg

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


def get_routes_Dict(user=None, data=None):
    from ReferenceDataApp.models import Airport, Country, City

    # if not user and user.is_authenticated:
    #     errors_Dict = {
    #         'errors': {
    #             'all__': f'ошибка идентификации пользователя'
    #         }
    #     }
    #     return errors_Dict
    kwargs = {}
    if user:
        kwargs.update({
            'owner': user
        })

    from_el = None
    to_el = None

    res_Dict = {}

    if data:
        for key, val in data.items():
            if val:
                if key == 'weight':
                    weight_list = val.split(';')
                    if weight_list[0]:
                        kwargs.update({f'{key}__gte': int(weight_list[0])})
                    if weight_list[1]:
                        kwargs.update({f'{key}__lte': int(weight_list[1])})

                if key == 'type_transport':
                    items_list = val.split(',')
                    kwargs.update({f'{key}__in': items_list})


                if key in (
                    'departure_DT', 'arrival_DT'
                ):
                    dates = val.split(' - ')
                    kwargs.update({
                        f'{key}__date__gte': datetime.strptime(dates[0], '%d.%m.%Y'),
                        f'{key}__date__lte': datetime.strptime(dates[1], '%d.%m.%Y').replace(hour=23, minute=59, second=59)
                    })

                if key not in (
                    'from_address_point_txt', 'to_address_point_txt', 'csrfmiddlewaretoken', 'sort', 'weight',
                    'from_el', 'to_el', 'from_address_point', 'to_address_point', 'type_transport',
                    'departure_DT', 'arrival_DT'
                ):
                    kwargs.update({key: val})

                if key == 'from_address_point':
                    kwargs.update({f'from_city__id': val})
                    res_Dict.update({
                        'from_address_point_txt': get_country_n_city_str_by_type_transport_and_address_point(
                            'road', val
                        )
                    })

                if key == 'to_address_point':
                    kwargs.update({f'to_city__id': val})
                    res_Dict.update({
                        'to_address_point_txt': get_country_n_city_str_by_type_transport_and_address_point(
                            'road', val
                        )
                    })

                if key == 'from_el':
                    from_el = int(val)
                if key == 'to_el':
                    to_el = int(val)

    routes = Route.objects.filter(**kwargs).order_by('departure_DT', 'arrival_DT', '-modifiedDT')
    routes_count = routes.count()

    if from_el and to_el:
        routes = routes[from_el:to_el]
    elif from_el:
        routes = routes[from_el:]
    elif to_el:
        routes = routes[:to_el]
    else:
        to_el = 25
        routes = routes[:to_el]

    last_block = False
    if not to_el or to_el >= routes_count:
        last_block = True



    try:

        for route in routes:

            try:

                if route.type_transport == 'avia':
                    route.from_airport = Airport.objects.get(id=route.from_address_point)
                    route.to_airport = Airport.objects.get(id=route.to_address_point)
                    route.from_city = route.from_airport.city
                    route.to_city = route.to_airport.city
                else:
                    route.from_city = City.objects.get(id=route.from_address_point)
                    route.to_city = City.objects.get(id=route.to_address_point)

                route.from_country = route.from_city.country
                route.to_country = route.to_city.country
            except Exception as e:
                msg = f'get_routes_for_user get route Error = {str(e)}'
                print(msg)

        res_Dict.update({
            'routes': routes,
            'last_block': last_block,
            'last_el': to_el
        })
        return res_Dict


    except Exception as e:
        msg = f'get_routes_for_user = {str(e)}'
        print(msg)
        errors_Dict = {
            'errors': {
                'all__': msg
            }
        }
        return errors_Dict