from django.db import models
from BaseModels.base_models import BaseModel
from SubscribesApp.models import Subscribe, SubscribeForUser
from AuthApp.models import User
from django.utils.translation import gettext as _

class SubscribeOrder(BaseModel):

    subscribe = models.ForeignKey(
        Subscribe, verbose_name=_('Подписка'),
        on_delete=models.SET_NULL, blank=True, null=True,
        related_name='subscribe_orders_for_subscribe'
    )

    user = models.ForeignKey(
        User, verbose_name=_('Пользователь'),
        on_delete=models.SET_NULL, blank=True, null=True,
        related_name='subscribe_orders_for_user'
    )

    subscribe_for_user = models.OneToOneField(
        SubscribeForUser, verbose_name=_('Подписка пользователя'),
        on_delete=models.SET_NULL, blank=True, null=True,
        related_name='subscribe_orders_for_user_subscribe'
    )

    sum = models.PositiveSmallIntegerField(verbose_name=_('Сумма'), default=0)
    currency = models.CharField(verbose_name=_('Валюта'), max_length=3, default='USD')
    segment = models.CharField(verbose_name=_('ID Сегмента'), null=True, default=None)
    merchant_order_id = models.CharField(verbose_name=_('merchant_order_id'), null=True, default=None)
    bank_order_id = models.CharField(verbose_name=_('ID заказа в банке'), null=True, default=None)

    status = models.CharField(verbose_name=_('Статус заказа в банке'), null=True, default=None)
    last_operation_status = models.CharField(verbose_name=_('Статус последней операции'), null=True, default=None)

    pay_page = models.URLField(verbose_name=_('Ссылка на страницу оплаты'), null=True, blank=True, default=None)

    class Meta:
        verbose_name = _('Заказ на подписку')
        verbose_name_plural = _('Заказы на подписки')

    def activate_subscribe_for_user(self):
        from datetime import datetime, timedelta

        kwargs = {
            'user': self.user,
            'subscribe': self.subscribe,
            'last_paid_DT': datetime.now(),
            'receive_finish_subscribe_msg': True,
            # 'enable': True,
        }

        from SubscribesApp.funcs import create_subscribe_by_data
        subscribe_for_user = create_subscribe_by_data(kwargs)
        self.subscribe_for_user = subscribe_for_user
        self.enable = False
        self.save()

        subscribe_for_user.activate(
            paid_period_from_DT=datetime.now(),
            paid_period_to_DT=datetime.now() + timedelta(hours=self.subscribe.period)
        )

        return self

    def __str__(self):
        res = 'Заказ'
        if self.subscribe:
            res += f' на подписку {self.subscribe.name}'
        if self.user:
            res += f' для {self.user.username}'

        if not res:
            res += f' {str(self.id)}'
        return res