# w.c.s. - web application for online forms
# Copyright (C) 2005-2019  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

from django.utils import six

from wcs.formdata import FormData


class CardData(FormData):
    def get_formdef(self):
        if self._formdef:
            return self._formdef
        from .carddef import CardDef
        type, id = self._names.split('-', 1)
        try:
            self._formdef = CardDef.get_by_urlname(id)
        except KeyError:
            self._formdef = None
        return self._formdef
    formdef = property(get_formdef)

    def get_data_source_structured_item(self):
        item = {
            'id': self.id,
            'text': self.digest,
        }
        for field in self.formdef.get_all_fields():
            if not field.varname:
                continue
            value = self.data and self.data.get(field.id)
            if isinstance(value, six.string_types):
                item[field.varname] = value
        return item
