import uuid

from sqlalchemy import Column, BigInteger
from sqlalchemy.orm import relationship

from .meta import (
    Base,
    RBase,
    UUIDType,
    foreign_key,
    now_timestamp,
    get_object_by_id,
)

from ..lib.currency import cents_to_dollars


class GiftCardTransaction(RBase, Base):
    """Tracks each time a gift card balance is used at checkout."""

    id = Column(UUIDType, primary_key=True, index=True)
    gift_card_id = Column(UUIDType, foreign_key("GiftCard", "id"), nullable=False)
    invoice_id = Column(UUIDType, foreign_key("Invoice", "id"), nullable=False)
    amount_in_cents = Column(BigInteger, nullable=False)
    created_timestamp = Column(BigInteger, nullable=False)

    gift_card = relationship(
        argument="GiftCard", uselist=False, lazy="joined",
        back_populates="transactions",
    )
    invoice = relationship(argument="Invoice", uselist=False, lazy="joined")

    def __init__(self, gift_card, invoice, amount_in_cents):
        self.id = uuid.uuid1()
        self.gift_card = gift_card
        self.invoice = invoice
        self.amount_in_cents = amount_in_cents
        self.created_timestamp = now_timestamp()

    @property
    def amount(self):
        return cents_to_dollars(self.amount_in_cents)


def get_gift_card_transaction_by_id(dbsession, transaction_id):
    return get_object_by_id(dbsession, transaction_id, GiftCardTransaction)
