from django import forms
from django.core.exceptions import ValidationError
from parts import models as parts_models

class MyTestForm(forms.Form):
    pass

class AddSubStorageForm(forms.Form):
    storage_name = forms.CharField(label="storage_name", initial='')
    responsible = forms.CharField(label='responsible_user')

class DeleteStockForm(forms.Form):
    stock_uuid = forms.UUIDField()

class EditWatermarkForm(forms.Form):
    stock_uuid = forms.UUIDField()
    watermark_active = forms.BooleanField(required=False) #If it is false, the webbrowser won't send it at all. Therefore we have to set it to required=False
    watermark = forms.IntegerField(min_value=0)

    def clean(self):
        cleaned_data = super().clean()
        id = cleaned_data.get("stock_uuid")
        
        if not id:
            raise ValidationError("No stock UUID given")

        stock = None
        try:
            stock = parts_models.Stock.objects.get(id=id)
        except:
            raise ValidationError("Stock with uuid %s does not exist" % (id))
        cleaned_data['stock'] = stock

        return cleaned_data

    def save(self):
        stock = self.cleaned_data['stock']
        active = self.cleaned_data['watermark_active']
        watermark = self.cleaned_data['watermark']

        if not active:
            watermark = -1

        stock.watermark = watermark
        stock.save()

class EditStockAmountForm(forms.Form):
    stock_uuid = forms.UUIDField()
    amount = forms.IntegerField(min_value=0)

    def clean(self):
        cleaned_data = super().clean()
        id = cleaned_data.get("stock_uuid")

        if not id:
            raise ValidationError("No stock UUID given")

        stock = None
        try:
            stock = parts_models.Stock.objects.get(id=id)
        except:
            raise ValidationError("Stock with uuid %s does not exist" % (id))
        cleaned_data['stock'] = stock

        return cleaned_data

    def save(self, increase: bool):
        stock = self.cleaned_data['stock']
        amount = self.cleaned_data['amount']

        if not increase:
            amount = -amount 

        return stock.atomic_increment(amount)