from django.db import models
from django.utils.translation import gettext_lazy as _
from BaseModels.base_models import BaseModel


type_transport_choices = [
    ('', _('-- Выберите cпособ перевозки --')),
    ('avia', _('Авиатранспорт')),
    ('road', _('Наземный транспорт'))
]

transfer_location_choices = (
    ('airport', _('В аэропорту')),
    ('city', _('По городу')),
    ('other', _('По договоренности'))
)

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

owner_type_choices = (
    ('customer', _('Заказчик')),
    ('mover', _('Перевозчик'))
)


class Route(BaseModel):
    from django.contrib.auth.models import User
    from ReferenceDataApp.models import City

    owner_type = models.CharField(
        choices=owner_type_choices, default='customer', verbose_name=_('Тип опреации'))

    type_transport = models.CharField(
        choices=type_transport_choices, default='', verbose_name=_('Выберите способ перевозки'))
    departure_DT = models.DateTimeField(default=True, verbose_name=_('Дата и время выезда'))
    arrival_DT = models.DateTimeField(default=True, verbose_name=_('Дата и время прибытия'))
    from_address_point = models.IntegerField(verbose_name=_('Пункт выезда'))
    to_address_point = models.IntegerField(verbose_name=_('Пункт приезда'))
    from_city = models.ForeignKey(
        City, verbose_name=_('Город отправки'), related_name='rel_routes_for_cityFrom', on_delete=models.SET_NULL,
        null=True, blank=True
    )
    to_city = models.ForeignKey(
        City, verbose_name=_('Город получения'), related_name='rel_routes_for_cityTo', on_delete=models.SET_NULL,
        null=True, blank=True
    )
    from_place = models.CharField(choices=transfer_location_choices, default='other',
                                   verbose_name=_('Откуда можете забрать?'))
    to_place = models.CharField(choices=transfer_location_choices, default='other',
                                 verbose_name=_('Куда можете доставить?'))
    cargo_type = models.CharField(choices=cargo_type_choices, default='parcel', verbose_name=_('Могу перевезти'))
    weight = models.IntegerField(verbose_name=_('Укажите вес до (кг)'))
    phone = models.CharField(verbose_name=_('Укажите номер для связи'))
    extra_phone = models.CharField(verbose_name=_('Дополнительный номер'), blank=True, null=True)
    receive_msg_by_email = models.BooleanField(default=False, verbose_name=_('Получать уведомления по E-mail'))
    receive_msg_by_sms = models.BooleanField(default=False, verbose_name=_('Получать уведомления по SMS'))
    owner = models.ForeignKey(User, verbose_name=_('Владелец'), related_name='rel_routes_for_owner', on_delete=models.CASCADE)

    def __str__(self):
        if self.name:
            return f'{self.name}'
        else:
            return str(self.id)


    class Meta:
        verbose_name = _(u'Маршрут')
        verbose_name_plural = _(u'Маршруты')
        ordering = ('name',)

    def from_country_n_city_str(self):
        res = _('Неизвестно')
        if self.from_city:
            res = self.from_city.get_country_n_city_str()

        return res

    def to_country_n_city_str(self):
        res = _('Неизвестно')
        if self.to_city:
            res = self.to_city.get_country_n_city_str()

        return res


    def get_address_points(self):
        from ReferenceDataApp.models import Airport, City

        try:
            if self.type_transport == 'avia':
                from_address_point_objs = Airport.objects.filter(id=self.from_address_point)
                from_address_point_Dict = from_address_point_objs.values(
                    'id', 'name', 'iata_code', 'city__name', 'city__country__name')[0]
                to_address_point_objs = Airport.objects.filter(id=self.to_address_point)
                to_address_point_Dict = to_address_point_objs.values(
                    'id', 'name', 'iata_code', 'city__name', 'city__country__name')[0]

                from_address_point_txt = f'{from_address_point_Dict["iata_code"]} - {from_address_point_Dict["name"]}'
                to_address_point_txt = f'{to_address_point_Dict["iata_code"]} - {to_address_point_Dict["name"]}'
            else:
                from_address_point_objs = City.objects.filter(id=self.from_address_point)
                from_address_point_Dict = from_address_point_objs.values(
                    'id', 'name', 'country__name')[0]
                to_address_point_objs = City.objects.filter(id=self.to_address_point)
                to_address_point_Dict = to_address_point_objs.values(
                    'id', 'name', 'country__name')[0]

                from_address_point_txt = f'{from_address_point_Dict["name"]} / {from_address_point_Dict["country__name"]}'
                to_address_point_txt = f'{to_address_point_Dict["name"]} / {to_address_point_Dict["country__name"]}'

            return {
                'from_address_point_obj': from_address_point_objs[0],
                'from_address_point_Dict': from_address_point_Dict,
                'from_address_point_txt': from_address_point_txt,

                'to_address_point_obj': to_address_point_objs[0],
                'to_address_point_Dict': to_address_point_Dict,
                'to_address_point_txt': to_address_point_txt,
            }


        except Exception as e:
            print(f'get_address_points Error = {str(e)}')
            return None