# passerelle.contrib.fake_family
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

from jsonfield import JSONField

from passerelle.base.models import BaseResource
from .default_database import default_database


class FakeFamily(BaseResource):
    jsondatabase = JSONField(_('Fake Database (JSON)'),
            blank=True)

    category = _('Business Process Connectors')

    class Meta:
        verbose_name = _('Fake Family System')

    def save(self, *args, **kwargs):
        if not self.jsondatabase:
            self.jsondatabase = default_database()
        super(FakeFamily, self).save(*args, **kwargs)

    @classmethod
    def get_icon_class(cls):
        return 'family'

    @classmethod
    def get_verbose_name(cls):
        return cls._meta.verbose_name

    def get_familyid_by_nameid(self, nameid):
        '''get family_id (or None) linked to the nameid, and do some checks'''
        adult_id = self.jsondatabase['links'].get(nameid)
        if not adult_id:
            return None
        family_ids = []
        for family_id, family_dict in self.jsondatabase['families'].items():
            if adult_id in family_dict['adults']:
                family_ids.append(family_id)
        if not family_ids:
            raise ObjectDoesNotExist('adult "%s" not found in a family' % adult_id)
        if len(family_ids) > 1:
            raise MultipleObjectsReturned('adult "%s" is in more than one family (%s)' % \
                                      (adult_id, family_ids))
        return family_ids[0]

    def get_list_of(self, kind, family_id):
        items = []
        for item_id in self.jsondatabase['families'][family_id][kind]:
            item_dict = self.jsondatabase[kind].get(item_id)
            item_dict['id'] = item_id
            items.append(item_dict)
        return items
