# barbacompta - accounting for dummies
# Copyright (C) 2010-2019 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.db import models

from .validators import validate_siret


class Update(models.Model):
    timestamp = models.DateTimeField(
        auto_now_add=True,
    )
    success = models.BooleanField(
        default=False,
    )
    message = models.TextField()


class Structure(models.Model):
    name = models.CharField(max_length=80)
    full_identifier = models.CharField(max_length=len('29202001300010') + 64, unique=True)
    siret = models.CharField(
        max_length=len('29202001300010'),
        validators=[validate_siret],
        db_index=True,
    )
    service_code = models.CharField(max_length=64, default='', blank=True)
    service_name = models.CharField(max_length=80, default='', blank=True)
    email = models.EmailField(null=True)
    engagement_obligatoire = models.BooleanField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not self.full_identifier:
            self.full_identifier = (self.siret + self.service_code)[: len('29202001300010') + 64]

    def __str__(self):
        return '%s%s%s (%s%s%s)>' % (
            self.name,
            ' - ' if self.service_name else '',
            self.service_name,
            self.siret,
            '-' if self.service_code else '',
            self.service_code,
        )

    class Meta:
        ordering = ('name', 'service_name')
        indexes = [models.Index(fields=['name', 'service_name'], name='name_idx')]
