#
# farmwork/forms.py
#

from django import forms
from django.utils.text import slugify
from .models import Farmwork


# ========================================================
# FARMWORK FORM
# ========================================================

class FarmworkForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(FarmworkForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Farmwork
        fields = [
            'job_role',
            'job_fruit',
            'job_pay',
            'job_pay_type',
            'job_start_date',
            'job_duration',
            'job_duration_type',
            'job_description',
            'con_first_name',
            'con_surname',
            'con_number',
            'con_email',
            'con_description',
            'acc_variety',
            'acc_price',
            'acc_price_type',
            'acc_description',
            'loc_street_address',
            'loc_city',
            'loc_state',
            'loc_post_code',
        ]

    # --
    # AUTO GENERATE SLUG ON SAVE
    # Credit: https://keyerror.com/blog/automatically-generating-unique-slugs-in-django
    # --

    def save(self):

        if self.instance.pk:
            return super(FarmworkForm, self).save()

        instance = super(FarmworkForm, self).save(commit=False)
        instance.slug = slugify(instance.get_job_fruit_display() + '-' + instance.get_job_role_display() + '-in-' + instance.loc_city)
        instance.save()

        return instance
