from django.conf import settings
from django.db import models

from djino.models import SyncModel
from djino.sync_meta import SyncScope


class Tag(SyncModel):
    name = models.CharField(max_length=50, unique=True)
    color = models.CharField(max_length=7, default="#000000")

    class SyncMeta:
        scope = SyncScope.GLOBAL
        client_writable = False


class Note(SyncModel):
    title = models.CharField(max_length=200)
    body = models.TextField(blank=True)
    status = models.CharField(
        max_length=20,
        choices=[
            ("draft", "Draft"),
            ("published", "Published"),
            ("archived", "Archived"),
        ],
    )
    priority = models.IntegerField(default=0)
    is_pinned = models.BooleanField(default=False)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    tags = models.ManyToManyField(Tag, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class SyncMeta:
        scope = SyncScope.USER
        owner_field = "author"


class SharedNote(SyncModel):
    note = models.ForeignKey(Note, on_delete=models.CASCADE)
    shared_with = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    can_edit = models.BooleanField(default=False)

    class SyncMeta:
        scope = SyncScope.SHARED
        sync_filter = staticmethod(lambda user: models.Q(shared_with=user))
        client_writable = True
        write_check = staticmethod(
            lambda user, instance: instance.shared_with == user and instance.can_edit
        )


class DefaultsModel(SyncModel):
    """Model with no SyncMeta — should get defaults."""

    name = models.CharField(max_length=100)
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    class SyncMeta:
        scope = SyncScope.USER
        owner_field = "owner"
