# w.c.s. - web application for online forms
# Copyright (C) 2005-2020  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 wcs.qommon import misc, get_logger
from wcs.qommon.xml_storage import XmlStorableObject


class MailTemplate(XmlStorableObject):
    _names = 'mail-templates'
    _xml_tagname = 'mail-template'

    name = None
    slug = None
    description = None
    subject = None
    body = None
    attachments = []

    # declarations for serialization
    XML_NODES = [
            ('name', 'str'),
            ('slug', 'str'),
            ('description', 'str'),
            ('subject', 'str'),
            ('body', 'str'),
            ('attachments', 'str_list'),
    ]

    def __init__(self, name=None):
        XmlStorableObject.__init__(self)
        self.name = name

    def store(self):
        if self.slug is None:
            # set slug if it's not yet there
            self.slug = self.get_new_slug()
        super(MailTemplate, self).store()

    def get_new_slug(self):
        new_slug = misc.simplify(self.name, space='-')
        base_new_slug = new_slug
        suffix_no = 0
        known_slugs = {x.slug: x.id for x in self.select(ignore_migration=True, ignore_errors=True)}
        while True:
            if not new_slug in known_slugs:
                break
            suffix_no += 1
            new_slug = '%s-%s' % (base_new_slug, suffix_no)
        return new_slug

    def get_places_of_use(self):
        from wcs.workflows import Workflow
        for workflow in Workflow.select(ignore_errors=True, ignore_migration=True):
            for item in workflow.get_all_items():
                if item.key != 'sendmail':
                    continue
                if item.mail_template == self.slug:
                    yield workflow
                    break

    def is_in_use(self):
        return any(self.get_places_of_use())

    @classmethod
    def get_as_options_list(cls):
        options = []
        for mail_template in cls.select(order_by='name'):
            options.append((mail_template.slug, mail_template.name, mail_template.slug))
        return options

    @classmethod
    def get_by_slug(cls, slug):
        objects = [x for x in cls.select() if x.slug == slug]
        if objects:
            return objects[0]
        get_logger().warn("mail template '%s' does not exist" % slug)
        return None
