# Path: app/card/forms.py
# class CardForm(forms.Form):
#     name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False)
#     value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560)
#     long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False)
#     active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True)
# 
# class FeedForm(forms.Form):
#     player = forms.ModelChoiceField(Player.objects.all(), label="玩家")
# 
# Path: app/models.py
# class Card(models.Model):
#     def random():
#         return str(get_random_string(16))
#     cid = models.CharField(max_length=16,
#                            primary_key=True,
#                            default=random,
#                            verbose_name="Card ID",
#                            help_text="The unique ID for the points card.")
#     value = models.IntegerField(default="1",
#                                 verbose_name="Value",
#                                 help_text="The value of the points card.")
#     active = models.BooleanField(default=True, verbose_name="Active?")
#     retrieved = models.BooleanField(default=False, verbose_name="Retrieved")
#     name = models.CharField(
#         max_length=32,
#         verbose_name="Name",
#         help_text="Name of the card.",
#         blank=True)
#     long_desc = models.TextField(verbose_name="Descriptions",
#                                  help_text="Long descriptions about the card.",
#                                  blank=True)
#     issuer = models.ForeignKey(User, related_name="issued_card")
#     capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True)
# 
#     def __str__(self):
#         if self.active and not self.retrieved:
#             return (str(self.name) + " (" + str(self.cid) + "), "
#                     "active, " + str(self.value) + " points.")
#         elif not self.active and self.retrieved:
#             return (str(self.name) + " (" + str(self.cid) + "), "
#                     "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.")
#         else:
#             return (str(self.name) + " (" + str(self.cid) + "), "
#                     "inactive, " + str(self.value) + " points.")
# 
#     class Meta:
#         permissions = (
#             ('read_card', 'can view card detail message'),
#             ('get_card', 'can capture card'),
#             ('toggle_card', 'can active/inactive card'),
#             ('gen_card', 'can generate card within limit'),
#             ('feed_card', 'can directly send card to someone'),
#             ('view_cardlist', 'can list all card'),
# 
#             ('master', 'game master'),
#             ('worker', 'normal staff'),
#         )
# 
# class History(models.Model):
#     ACTION_CODE = {
#         1: "建立卡片",
#         2: "編輯卡片",
#         3: "關閉卡片",
#         4: "啟動卡片",
#         10: "獲得卡片",
#         0xfeed: "餵食卡片",
#     }
# 
#     no = models.AutoField(primary_key=True)
#     action = models.IntegerField(choices=list(ACTION_CODE.items()))
#     user = models.ForeignKey(User)
#     card = models.ForeignKey(Card)
#     comment = models.CharField(max_length=255)
#     date = models.DateTimeField(auto_now_add=True)
# 
#     @property
#     def action_explain(self):
#         return History.ACTION_CODE[self.action]
# 
#     class Meta:
#         permissions = (
#             ('view_history', 'can view history'),
#         )


from app.card.forms import CardForm, FeedForm
from app.models import Card, History
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.db import transaction
                        "title": "編輯失敗",
                        "next_page": reverse('edit card', id),
                    })
    else:
        raise PermissionDenied


def get(request, id=None):
    if not request.user.is_authenticated():
        # Anonymous User
        return render(
            request, "submit.html", {
                "success": False,
                "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                "title": "未登入！"}, status=403)
    elif request.user.has_perm('app.get_card'):
        # player
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not card.retrieved and card.active:
            # Add points
            with transaction.atomic():
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()

# Path: app/card/forms.py
# class CardForm(forms.Form):
#     name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False)
#     value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560)
#     long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False)
#     active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True)
# 
# class FeedForm(forms.Form):
#     player = forms.ModelChoiceField(Player.objects.all(), label="玩家")
# 
# Path: app/models.py
# class Card(models.Model):
#     def random():
#         return str(get_random_string(16))
#     cid = models.CharField(max_length=16,
#                            primary_key=True,
#                            default=random,
#                            verbose_name="Card ID",
#                            help_text="The unique ID for the points card.")
#     value = models.IntegerField(default="1",
#                                 verbose_name="Value",
#                                 help_text="The value of the points card.")
#     active = models.BooleanField(default=True, verbose_name="Active?")
#     retrieved = models.BooleanField(default=False, verbose_name="Retrieved")
#     name = models.CharField(
#         max_length=32,
#         verbose_name="Name",
#         help_text="Name of the card.",
#         blank=True)
#     long_desc = models.TextField(verbose_name="Descriptions",
#                                  help_text="Long descriptions about the card.",
#                                  blank=True)
#     issuer = models.ForeignKey(User, related_name="issued_card")
#     capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True)
# 
#     def __str__(self):
#         if self.active and not self.retrieved:
#             return (str(self.name) + " (" + str(self.cid) + "), "
#                     "active, " + str(self.value) + " points.")
#         elif not self.active and self.retrieved:
#             return (str(self.name) + " (" + str(self.cid) + "), "
#                     "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.")
#         else:
#             return (str(self.name) + " (" + str(self.cid) + "), "
#                     "inactive, " + str(self.value) + " points.")
# 
#     class Meta:
#         permissions = (
#             ('read_card', 'can view card detail message'),
#             ('get_card', 'can capture card'),
#             ('toggle_card', 'can active/inactive card'),
#             ('gen_card', 'can generate card within limit'),
#             ('feed_card', 'can directly send card to someone'),
#             ('view_cardlist', 'can list all card'),
# 
#             ('master', 'game master'),
#             ('worker', 'normal staff'),
#         )
# 
# class History(models.Model):
#     ACTION_CODE = {
#         1: "建立卡片",
#         2: "編輯卡片",
#         3: "關閉卡片",
#         4: "啟動卡片",
#         10: "獲得卡片",
#         0xfeed: "餵食卡片",
#     }
# 
#     no = models.AutoField(primary_key=True)
#     action = models.IntegerField(choices=list(ACTION_CODE.items()))
#     user = models.ForeignKey(User)
#     card = models.ForeignKey(Card)
#     comment = models.CharField(max_length=255)
#     date = models.DateTimeField(auto_now_add=True)
# 
#     @property
#     def action_explain(self):
#         return History.ACTION_CODE[self.action]
# 
#     class Meta:
#         permissions = (
#             ('view_history', 'can view history'),
#         )


# Path: app/card/views.py
from app.card.forms import CardForm, FeedForm
from app.models import Card, History
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.db import transaction

                        "title": "編輯失敗",
                        "next_page": reverse('edit card', id),
                    })
    else:
        raise PermissionDenied


def get(request, id=None):
    if not request.user.is_authenticated():
        # Anonymous User
        return render(
            request, "submit.html", {
                "success": False,
                "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                "title": "未登入！"}, status=403)
    elif request.user.has_perm('app.get_card'):
        # player
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not card.retrieved and card.active:
            # Add points
            with transaction.atomic():
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()

                record = History(action=10, user=request.user, card=card)