# The COPYRIGHT file at the top level of this repository contains
# the full copyright notices and license terms.

from trytond.model import Index, ModelSQL, ModelView, Unique, fields
from trytond.pool import Pool
from trytond.pyson import Eval
from trytond.transaction import Transaction


class CollectionMixin:
    user = fields.Many2One('res.user', 'User', required=True,
        ondelete='RESTRICT', readonly=True)
    name = fields.Char("Name", required=True)
    url = fields.Char('URL', required=True,
        states={
            'readonly': Eval('id', 0) > 0
            })
    description = fields.Char("Description")
    ctag = fields.Char('CTag', readonly=True)


class CardDAVCollection(ModelSQL, ModelView, CollectionMixin):
    "CardDAV Collection (Addressbook)"
    __name__ = "webdav.carddav_collection"

    @classmethod
    def __setup__(cls):
        super().__setup__()
        t = cls.__table__()
        cls._sql_constraints.extend([
                ('user_url_uniq', Unique(t, t.user, t.url),
                    'dav_client.msg_url_unique_per_user'),
                ])
        cls._sql_indexes.update({
            Index(t, (t.url, Index.Equality())),
            Index(t, (t.ctag, Index.Equality())),
        })

    #@classmethod
    #def create(cls, vlist):
    #    pool = Pool()
    #    User = pool.get('res.user')

    #    user = User(Transaction().user)
    #    records = super().create(vlist)
    #    for record in records:
    #    TODO: put in on worker, or save before calling?
    # TypeError: 'NoneType' object is not iterable
    #        print('***', user.ensure_dav_collection(record))
    #        print('***', user.ensure_dav_collection(record))
    #        try:
    #            user.ensure_dav_collection(record)
    #        except:
    #            pass

    @classmethod
    def update_url(cls, collection, new_url):
        """
        Used as queue run in a separate writeable transaction.
        """
        collection = cls(collection.id)
        collection.url = new_url
        collection.save()


class CalDAVCollection(ModelSQL, ModelView, CollectionMixin):
    "CalDAV Collection (Calendar)"
    __name__ = "webdav.caldav_collection"

    @classmethod
    def __setup__(cls):
        super().__setup__()
        t = cls.__table__()
        cls._sql_constraints.extend([
                ('user_url_uniq', Unique(t, t.user, t.url),
                    'dav_client.msg_url_unique_per_user'),
                ])
        cls._sql_indexes.update({
            Index(t, (t.url, Index.Equality())),
            Index(t, (t.ctag, Index.Equality())),
        })
