import re

from django import forms

from ..models import FloorMap
from ..storage import save_file_to_storage


class FloorMapForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(FloorMapForm, self).__init__(*args, **kwargs)
        floor_field = self.fields['floor']
        floor_field.queryset = floor_field.queryset.filter(intranet_status=1)
        floor_field.choices = [
            (f['id'], '{office__name} —> {name}'.format(**f))
            for f in (
                floor_field.queryset
                .values('id', 'name', 'office__name')
                .order_by('office', 'num')
            )
        ]

    image = forms.FileField()

    def save(self, **kwargs):
        obj = super(FloorMapForm, self).save(**kwargs)

        obj.file_name = get_file_name(obj)
        obj.save()

        img = self.files.get('image')
        save_file_to_storage(obj.file_name, img)
        return obj

    class Meta:
        model = FloorMap
        fields = ('floor',)


def get_file_name(floor_map):
    office_name = floor_map.floor.office.name_en.strip().lower()
    office_name = re.sub(r'[^a-z0-9\s]', '', office_name)
    office_name = re.sub(r'\s', '-', office_name)

    floor_num = str(floor_map.floor.num).replace('-', 'u')

    return '{office_name}-{floor_num}-{map_id}'.format(
        office_name=office_name,
        floor_num=floor_num,
        map_id=floor_map.id,
    )
