# Path: payway/accounts/conf/settings.py
# ADD_MONEY_INITIAL_SUM = getattr(settings, 'ADD_MONEY_INITIAL_SUM', 10)
# 
# Path: payway/accounts/forms/add_money.py
# class AddMoneyForm(forms.Form):
#     money_amount = forms.DecimalField(
#         label=_('money amount'),
#         min_value=MIN_MONEY_VALUE,
#         max_digits=MAX_MONEY_DIGITS,
#         decimal_places=MAX_MONEY_PLACES,
#     )
#     invoice_uid = forms.IntegerField(max_value=RandomUIDAbstractModel.MAX_UID, widget=forms.HiddenInput())
# 
#     payment_system = ChoiceField(
#         label=_('payment system'),
#         widget=RadioSelect,
#         choices=PAYMENT_SYSTEM_CHOICES
#     )
# 
# PAYMENT_SYSTEM_CHOICES = (
#     ('webmoney_add_money', 'Webmoney WMR'),
#     ('qiwi_add_money', 'Qiwi RUB'),
# )
# 
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
# 
#     account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
#     money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
#     money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
#     objects = ChainableQuerySetManager(InvoiceQuerySet)
# 
#     class Meta:
#         verbose_name = _('invoice')
#         verbose_name_plural = _('invoices')
#         db_table = 'payway_invoices'
# 
#     def __init__(self, *args, **kwargs):
#         money_amount = kwargs.get('money_amount') or None
#         if money_amount:
#             kwargs.setdefault('money_amount_without_percent', money_amount)
#         super(Invoice, self).__init__(*args, **kwargs)
# 
#     def get_success_response_payments(self):
#         return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
# 
#     def __unicode__(self):
#         return u'{0}'.format(self.uid)
# 
#     def update_money_amount_with_percent(self, percent=0.0):
#         self.money_amount_without_percent = self.money_amount
#         self.money_amount += round_down(percent % self.money_amount)
#         self.save()
# 
# class Account(RandomUIDAbstractModel):
#     user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
#     currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
# 
#     class Meta:
#         verbose_name = _('account')
#         verbose_name_plural = _('accounts')
#         permissions = (('can_view_account_report', 'Can view account report'),)
#         db_table = 'payway_accounts'
# 
#     @property
#     def currency(self):
#         currency = None
#         if self.currency_code:
#             currency = get_currency(self.currency_code)
#         return currency
# 
#     def __unicode__(self):
#         return u"{0} {1}".format(self.uid, self.currency)
# 
#     def get_balance(self):
#         sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
#         return round_down(Money(sum, self.currency))
# 
#     def withdraw(self, money, allow_overdraft=False):
#         self.assert_correct_currency(money)
# 
#         if money < Money(0, self.currency):
#             raise ValueError("You can't withdraw a negative amount")
# 
#         if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
#             raise Overdraft
# 
#         return Transaction.objects.create(
#             account=self,
#             money_amount=money * '-1.0',
#         )
# 
#     def add(self, money):
#         self.assert_correct_currency(money)
# 
#         if money < Money(0, self.currency):
#             raise ValueError("You can't add a negative money amount")
# 
#         return Transaction.objects.create(
#             account=self,
#             money_amount=money,
#         )
# 
#     def transfer(self, money, to_account):
#         self.assert_correct_currency(money)
# 
#         if money < Money(0, self.currency):
#             raise ValueError("You can't transfer a negative money amount")
# 
#         self.withdraw(money)
# 
#         return Transaction.objects.create(
#             account=to_account,
#             money_amount=money,
#         )
# 
#     def assert_correct_currency(self, money):
#         if money.currency != self.currency:
#             raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))


from django.shortcuts import redirect, get_object_or_404
from django.views.generic.base import TemplateView
from moneyed.classes import Money
from payway.accounts.conf.settings import ADD_MONEY_INITIAL_SUM
from payway.accounts.forms.add_money import AddMoneyForm, PAYMENT_SYSTEM_CHOICES
from payway.accounts.models import Invoice, Account


class AddMoneyView(TemplateView):
    template_name = 'accounts/add_money.html'

    def get(self, request, *args, **kwargs):

        account_uid = int(kwargs.get('account_uid', -1))
        invoice_uid = int(kwargs.get('invoice_uid', -1))
        account = get_object_or_404(Account, uid=account_uid)

        invoice, created = Invoice.objects.get_or_create(
            uid=invoice_uid,
            account=account,
            defaults={
                'account': account,
                'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
            }
        )

        context = super(AddMoneyView, self).get_context_data(**kwargs)
        context['add_money_form'] = AddMoneyForm({
            'money_amount': invoice.money_amount_without_percent.amount,
            'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
            'invoice_uid': invoice.uid
        })

        return self.render_to_response(context)

    def post(self, request):

# Path: payway/accounts/conf/settings.py
# ADD_MONEY_INITIAL_SUM = getattr(settings, 'ADD_MONEY_INITIAL_SUM', 10)
# 
# Path: payway/accounts/forms/add_money.py
# class AddMoneyForm(forms.Form):
#     money_amount = forms.DecimalField(
#         label=_('money amount'),
#         min_value=MIN_MONEY_VALUE,
#         max_digits=MAX_MONEY_DIGITS,
#         decimal_places=MAX_MONEY_PLACES,
#     )
#     invoice_uid = forms.IntegerField(max_value=RandomUIDAbstractModel.MAX_UID, widget=forms.HiddenInput())
# 
#     payment_system = ChoiceField(
#         label=_('payment system'),
#         widget=RadioSelect,
#         choices=PAYMENT_SYSTEM_CHOICES
#     )
# 
# PAYMENT_SYSTEM_CHOICES = (
#     ('webmoney_add_money', 'Webmoney WMR'),
#     ('qiwi_add_money', 'Qiwi RUB'),
# )
# 
# Path: payway/accounts/models.py
# class Invoice(RandomUIDAbstractModel, TimeStampedModel):
# 
#     account = models.ForeignKey(Account, related_name='invoices', verbose_name=_('account'))
#     money_amount = fields.MoneyField(_('money amount'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # for transmit
#     money_amount_without_percent = fields.MoneyField(_('money amount without percent'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES) # befor transmit
#     objects = ChainableQuerySetManager(InvoiceQuerySet)
# 
#     class Meta:
#         verbose_name = _('invoice')
#         verbose_name_plural = _('invoices')
#         db_table = 'payway_invoices'
# 
#     def __init__(self, *args, **kwargs):
#         money_amount = kwargs.get('money_amount') or None
#         if money_amount:
#             kwargs.setdefault('money_amount_without_percent', money_amount)
#         super(Invoice, self).__init__(*args, **kwargs)
# 
#     def get_success_response_payments(self):
#         return self.accounts_responsepayment_related.filter(is_OK=ResponsePayment.OK_STATUS.SUCCESS)
# 
#     def __unicode__(self):
#         return u'{0}'.format(self.uid)
# 
#     def update_money_amount_with_percent(self, percent=0.0):
#         self.money_amount_without_percent = self.money_amount
#         self.money_amount += round_down(percent % self.money_amount)
#         self.save()
# 
# class Account(RandomUIDAbstractModel):
#     user = models.ForeignKey(User, related_name='accounts', verbose_name=_('user'))
#     currency_code = models.CharField(_('currency code'), max_length=3, choices=CURRENCY_CHOICES, default=moneyed.RUB)
# 
#     class Meta:
#         verbose_name = _('account')
#         verbose_name_plural = _('accounts')
#         permissions = (('can_view_account_report', 'Can view account report'),)
#         db_table = 'payway_accounts'
# 
#     @property
#     def currency(self):
#         currency = None
#         if self.currency_code:
#             currency = get_currency(self.currency_code)
#         return currency
# 
#     def __unicode__(self):
#         return u"{0} {1}".format(self.uid, self.currency)
# 
#     def get_balance(self):
#         sum = Transaction.objects.filter(account=self, money_amount_currency=self.currency).sum_values()
#         return round_down(Money(sum, self.currency))
# 
#     def withdraw(self, money, allow_overdraft=False):
#         self.assert_correct_currency(money)
# 
#         if money < Money(0, self.currency):
#             raise ValueError("You can't withdraw a negative amount")
# 
#         if not allow_overdraft and (self.get_balance() - money) < Money(0, self.currency):
#             raise Overdraft
# 
#         return Transaction.objects.create(
#             account=self,
#             money_amount=money * '-1.0',
#         )
# 
#     def add(self, money):
#         self.assert_correct_currency(money)
# 
#         if money < Money(0, self.currency):
#             raise ValueError("You can't add a negative money amount")
# 
#         return Transaction.objects.create(
#             account=self,
#             money_amount=money,
#         )
# 
#     def transfer(self, money, to_account):
#         self.assert_correct_currency(money)
# 
#         if money < Money(0, self.currency):
#             raise ValueError("You can't transfer a negative money amount")
# 
#         self.withdraw(money)
# 
#         return Transaction.objects.create(
#             account=to_account,
#             money_amount=money,
#         )
# 
#     def assert_correct_currency(self, money):
#         if money.currency != self.currency:
#             raise ValueError("You can't add money with %s currency. Current currency %s" % (money.currency, self.currency))


# Path: payway/accounts/views/add_money.py
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.base import TemplateView
from moneyed.classes import Money
from payway.accounts.conf.settings import ADD_MONEY_INITIAL_SUM
from payway.accounts.forms.add_money import AddMoneyForm, PAYMENT_SYSTEM_CHOICES
from payway.accounts.models import Invoice, Account



class AddMoneyView(TemplateView):
    template_name = 'accounts/add_money.html'

    def get(self, request, *args, **kwargs):

        account_uid = int(kwargs.get('account_uid', -1))
        invoice_uid = int(kwargs.get('invoice_uid', -1))
        account = get_object_or_404(Account, uid=account_uid)

        invoice, created = Invoice.objects.get_or_create(
            uid=invoice_uid,
            account=account,
            defaults={
                'account': account,
                'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
            }
        )

        context = super(AddMoneyView, self).get_context_data(**kwargs)
        context['add_money_form'] = AddMoneyForm({
            'money_amount': invoice.money_amount_without_percent.amount,
            'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
            'invoice_uid': invoice.uid
        })

        return self.render_to_response(context)

    def post(self, request):

        form = AddMoneyForm(request.POST or None)