from Acquisition import aq_base
from datetime import datetime
from datetime import timedelta
from plone import api
from ploneintranet.layout.browser.base import BaseStatusView


class StatusView(BaseStatusView):
    """
    Shows the status of the user/group sync.
    """

    def get_last_sync(self, obj):
        """Check when obj was synced the last time"""
        return getattr(aq_base(obj), "last_sync", None)

    def check_user_sync_recent(self):
        portal = api.portal.get()
        profiles = portal.get("profiles", {})
        last_sync = self.get_last_sync(profiles)
        if not last_sync:
            return self.warn("user_sync_recent", "No sync recorded yet")
        now = datetime.now()
        msg = f"Last sync was {last_sync}"
        if now - last_sync < timedelta(hours=12):
            return self.ok("user_sync_recent", msg)
        elif now - last_sync < timedelta(hours=24):
            return self.warn("user_sync_recent", msg)
        else:
            return self.fail("user_sync_recent", msg)

    def check_group_sync_recent(self):
        portal = api.portal.get()
        groups = portal.get("groups", {})
        last_sync = self.get_last_sync(groups)
        if not last_sync:
            return self.warn("group_sync_recent", "No sync recorded yet")
        now = datetime.now()
        msg = f"Last sync was {last_sync}"
        if now - last_sync < timedelta(hours=12):
            return self.ok("group_sync_recent", msg)
        elif now - last_sync < timedelta(hours=24):
            return self.warn("group_sync_recent", msg)
        else:
            return self.fail("group_sync_recent", msg)
