# Path: shared_schema_tenants/models.py
# class Tenant(TimeStampedModel):
#     name = models.CharField(max_length=255)
#     slug = models.CharField(max_length=255, primary_key=True)
# 
#     if 'postgresql' in django_settings.DATABASES['default']['ENGINE']:
#         from django.contrib.postgres.fields import JSONField
#         extra_data = JSONField(blank=True, null=True,
#                                default=get_setting('DEFAULT_TENANT_EXTRA_DATA'))
#         settings = JSONField(blank=True, null=True,
#                              default=get_setting('DEFAULT_TENANT_SETTINGS'))
#     else:
#         _extra_data = models.TextField(blank=True, null=True,
#                                        validators=[validate_json],
#                                        default=json.dumps(get_setting('DEFAULT_TENANT_EXTRA_DATA')))
#         _settings = models.TextField(blank=True, null=True,
#                                      validators=[validate_json],
#                                      default=json.dumps(get_setting('DEFAULT_TENANT_SETTINGS')))
# 
#         @property
#         def extra_data(self):
#             import json
#             return json.loads(self._extra_data)
# 
#         @extra_data.setter
#         def extra_data(self, value):
#             import json
#             self._extra_data = json.dumps(value)
# 
#         @property
#         def settings(self):
#             import json
#             return json.loads(self._settings)
# 
#         @settings.setter
#         def settings(self, value):
#             import json
#             self._settings = json.dumps(value)
# 
#     def __str__(self):
#         return self.name
# 
# class TenantSite(TimeStampedModel, SingleTenantModelMixin):
#     tenant = models.ForeignKey('Tenant', related_name="tenant_sites")
#     site = models.OneToOneField(Site, related_name="tenant_site")
# 
#     def __str__(self):
#         return '%s - %s' % (self.tenant.name, self.site.domain)
# 
# Path: shared_schema_tenants/helpers/tenants.py
# def create_tenant(name, slug, extra_data, domains=[], user=None):
#     from shared_schema_tenants.models import Tenant
#     with transaction.atomic():
#         tenant = Tenant.objects.create(
#             name=name, slug=slug, extra_data=extra_data)
# 
#         if len(domains) > 0:
#             for domain in domains:
#                 site = Site.objects.create(name=name, domain=domain)
#                 tenant.tenant_sites.create(site=site)
# 
#         if user:
#             rel = tenant.relationships.create(user=user)
#             rel.groups.add(create_default_tenant_groups()[0])
# 
#         return tenant
# 
# def update_tenant(tenant, name=None, slug=None, extra_data=None):
#     from shared_schema_tenants.models import Tenant  # noqa
#     from shared_schema_tenants.helpers import TenantExtraDataHelper
#     with transaction.atomic():
#         tenant.name = name if name else tenant.name
#         tenant.slug = slug if slug else tenant.slug
# 
#         extra_data_helper = TenantExtraDataHelper(instance=tenant)
#         tenant = extra_data_helper.update_fields(extra_data if extra_data else {}, commit=False)
# 
#         tenant.save()
# 
#         return tenant
# 
# def get_current_tenant():
#     from shared_schema_tenants.middleware import TenantMiddleware
#     return TenantMiddleware.get_current_tenant()
# 
# Path: shared_schema_tenants/helpers/tenant_extra_data.py
# class TenantExtraDataHelper(TenantJSONFieldHelper):
# 
#     def __init__(self, instance=None):
#         super(TenantExtraDataHelper, self).__init__(
#             instance_field_name='extra_data', instance=instance,
#             tenant_fields=get_setting('DEFAULT_TENANT_EXTRA_DATA_FIELDS'),
#             tenant_default_fields_values=get_setting('DEFAULT_TENANT_EXTRA_DATA'))
# 
# Path: shared_schema_tenants/helpers/tenant_settings.py
# class TenantSettingsHelper(TenantJSONFieldHelper):
# 
#     def __init__(self, instance=None):
#         super(TenantSettingsHelper, self).__init__(
#             instance_field_name='settings', instance=instance,
#             tenant_fields=get_setting('DEFAULT_TENANT_SETTINGS_FIELDS'),
#             tenant_default_fields_values=get_setting('DEFAULT_TENANT_SETTINGS'))


from django.db import transaction
from django.utils.text import ugettext_lazy as _
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from rest_framework import serializers
from shared_schema_tenants.models import (Tenant, TenantSite)
from shared_schema_tenants.helpers.tenants import (
    create_tenant, update_tenant, get_current_tenant)
from shared_schema_tenants.helpers import (
    TenantSettingsHelper, TenantExtraDataHelper)
            raise serializers.ValidationError(e.message_dict)
        else:
            return validated_extra_data

    def create(self, validated_data):
        return create_tenant(user=self.context['request'].user, **validated_data)

    def update(self, instance, validated_data):
        return update_tenant(instance, **validated_data)


class TenantSettingsSerializer(serializers.Serializer):

    def is_valid(self, raise_exception=False):
        settings_helper = TenantSettingsHelper()
        try:
            self._validated_data = settings_helper.validate_fields(
                self.context, self.initial_data, self.partial)
        except ValidationError as exc:
            self._validated_data = {}
            self._errors = exc.detail
        else:
            self._errors = {}

        if self._errors and raise_exception:
            raise ValidationError(self.errors)

        return not bool(self._errors)

    def create(self, validated_data):

# Path: shared_schema_tenants/models.py
# class Tenant(TimeStampedModel):
#     name = models.CharField(max_length=255)
#     slug = models.CharField(max_length=255, primary_key=True)
# 
#     if 'postgresql' in django_settings.DATABASES['default']['ENGINE']:
#         from django.contrib.postgres.fields import JSONField
#         extra_data = JSONField(blank=True, null=True,
#                                default=get_setting('DEFAULT_TENANT_EXTRA_DATA'))
#         settings = JSONField(blank=True, null=True,
#                              default=get_setting('DEFAULT_TENANT_SETTINGS'))
#     else:
#         _extra_data = models.TextField(blank=True, null=True,
#                                        validators=[validate_json],
#                                        default=json.dumps(get_setting('DEFAULT_TENANT_EXTRA_DATA')))
#         _settings = models.TextField(blank=True, null=True,
#                                      validators=[validate_json],
#                                      default=json.dumps(get_setting('DEFAULT_TENANT_SETTINGS')))
# 
#         @property
#         def extra_data(self):
#             import json
#             return json.loads(self._extra_data)
# 
#         @extra_data.setter
#         def extra_data(self, value):
#             import json
#             self._extra_data = json.dumps(value)
# 
#         @property
#         def settings(self):
#             import json
#             return json.loads(self._settings)
# 
#         @settings.setter
#         def settings(self, value):
#             import json
#             self._settings = json.dumps(value)
# 
#     def __str__(self):
#         return self.name
# 
# class TenantSite(TimeStampedModel, SingleTenantModelMixin):
#     tenant = models.ForeignKey('Tenant', related_name="tenant_sites")
#     site = models.OneToOneField(Site, related_name="tenant_site")
# 
#     def __str__(self):
#         return '%s - %s' % (self.tenant.name, self.site.domain)
# 
# Path: shared_schema_tenants/helpers/tenants.py
# def create_tenant(name, slug, extra_data, domains=[], user=None):
#     from shared_schema_tenants.models import Tenant
#     with transaction.atomic():
#         tenant = Tenant.objects.create(
#             name=name, slug=slug, extra_data=extra_data)
# 
#         if len(domains) > 0:
#             for domain in domains:
#                 site = Site.objects.create(name=name, domain=domain)
#                 tenant.tenant_sites.create(site=site)
# 
#         if user:
#             rel = tenant.relationships.create(user=user)
#             rel.groups.add(create_default_tenant_groups()[0])
# 
#         return tenant
# 
# def update_tenant(tenant, name=None, slug=None, extra_data=None):
#     from shared_schema_tenants.models import Tenant  # noqa
#     from shared_schema_tenants.helpers import TenantExtraDataHelper
#     with transaction.atomic():
#         tenant.name = name if name else tenant.name
#         tenant.slug = slug if slug else tenant.slug
# 
#         extra_data_helper = TenantExtraDataHelper(instance=tenant)
#         tenant = extra_data_helper.update_fields(extra_data if extra_data else {}, commit=False)
# 
#         tenant.save()
# 
#         return tenant
# 
# def get_current_tenant():
#     from shared_schema_tenants.middleware import TenantMiddleware
#     return TenantMiddleware.get_current_tenant()
# 
# Path: shared_schema_tenants/helpers/tenant_extra_data.py
# class TenantExtraDataHelper(TenantJSONFieldHelper):
# 
#     def __init__(self, instance=None):
#         super(TenantExtraDataHelper, self).__init__(
#             instance_field_name='extra_data', instance=instance,
#             tenant_fields=get_setting('DEFAULT_TENANT_EXTRA_DATA_FIELDS'),
#             tenant_default_fields_values=get_setting('DEFAULT_TENANT_EXTRA_DATA'))
# 
# Path: shared_schema_tenants/helpers/tenant_settings.py
# class TenantSettingsHelper(TenantJSONFieldHelper):
# 
#     def __init__(self, instance=None):
#         super(TenantSettingsHelper, self).__init__(
#             instance_field_name='settings', instance=instance,
#             tenant_fields=get_setting('DEFAULT_TENANT_SETTINGS_FIELDS'),
#             tenant_default_fields_values=get_setting('DEFAULT_TENANT_SETTINGS'))


# Path: shared_schema_tenants/serializers.py
from django.db import transaction
from django.utils.text import ugettext_lazy as _
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from rest_framework import serializers
from shared_schema_tenants.models import (Tenant, TenantSite)
from shared_schema_tenants.helpers.tenants import (
    create_tenant, update_tenant, get_current_tenant)
from shared_schema_tenants.helpers import (
    TenantSettingsHelper, TenantExtraDataHelper)

            raise serializers.ValidationError(e.message_dict)
        else:
            return validated_extra_data

    def create(self, validated_data):
        return create_tenant(user=self.context['request'].user, **validated_data)

    def update(self, instance, validated_data):
        return update_tenant(instance, **validated_data)


class TenantSettingsSerializer(serializers.Serializer):

    def is_valid(self, raise_exception=False):
        settings_helper = TenantSettingsHelper()
        try:
            self._validated_data = settings_helper.validate_fields(
                self.context, self.initial_data, self.partial)
        except ValidationError as exc:
            self._validated_data = {}
            self._errors = exc.detail
        else:
            self._errors = {}

        if self._errors and raise_exception:
            raise ValidationError(self.errors)

        return not bool(self._errors)

    def create(self, validated_data):

        settings_helper = TenantSettingsHelper()