from datetime import datetime
from plone import api
from plone.app.event.base import default_timezone
from plone.app.event.base import first_weekday
from plone.memoize.view import memoize
from plone.memoize.view import memoize_contextless
from plone.tiles import Tile
from ploneintranet.calendar.config import TZ_COOKIE_NAME
from ploneintranet.calendar.utils import get_timezone_info
from ploneintranet.layout.app import apps_container_id
from ploneintranet.workspace.utils import parent_workspace
from Products.CMFCore.permissions import ModifyPortalContent
from zope.component import getUtility
from zope.schema.interfaces import IVocabularyFactory


class FullCalendarTile(Tile):
    """FullCalendar as a tile, used in cal app and workspace calendar"""

    @memoize
    def calendar_url(self):
        """Return the URL of the calendar where events are fetched."""
        # calendar_context = api.portal.get()  # get all events and filter in frontend.
        calendar_context = self.workspace() or api.portal.get()
        return "{url}/@calendar_events?start=${{start_str}}&end=${{end_str}}".format(
            url=calendar_context.absolute_url()
        )

    @memoize_contextless
    def first_day(self):
        """pat-calendar wants the short day name to setup"""
        day_names = ["su", "mo", "tu", "we", "th", "fr", "sa"]
        return day_names[(first_weekday() + 1) % 7]

    @memoize
    def workspace(self):
        return parent_workspace(self.context)

    @property
    def app(self):
        portal = api.portal.get()
        return getattr(portal, apps_container_id).calendar

    @property
    def today(self):
        now = datetime.now()
        return now.strftime("%a, %d %b %Y")

    def get_start_date(self):
        current_date = datetime.now()
        current_day = current_date.day
        current_month = current_date.month
        current_year = current_date.year
        try:
            day = int(self.request.form.get("day") or current_day)
        except ValueError:
            day = current_day
        try:
            month = int(self.request.form.get("month") or current_month)
        except ValueError:
            month = current_month
        try:
            year = int(self.request.form.get("year") or current_year)
        except ValueError:
            year = current_year
        datestr = f"{year}-{month:0=2}-{day:0=2}"
        return datestr

    @memoize
    def can_edit(self):
        """Check edit permission on this context"""
        return api.user.has_permission(ModifyPortalContent, obj=self.context)

    def get_app_view(self):
        return api.content.get_view(self.app.app.lstrip("@"), self.app, self.request)

    def get_events(self):
        """get events for calendar, provide proper classes"""
        # Get all the users workspaces
        # Get all the users events
        # sort the workspaces depending on events available and the users
        # rights within the workspaces and invitee status on the event
        app_view = self.get_app_view()
        return app_view.get_events()

    def get_timezone_data(self):
        timezone_vocab = getUtility(
            IVocabularyFactory, "ploneintranet.calendar.timezones"
        )
        timezone_data = []
        for item in timezone_vocab:
            zoneinfo = get_timezone_info(item.token)
            timezone_data.append(zoneinfo)
        return timezone_data

    def get_user_timezone(self):
        return self.get_timezone_cookie(self)

    def set_user_timezone(self, tz):
        self.set_timezone_cookie(self, tz)

    def get_timezone_cookie(self, context):
        return context.request.get(TZ_COOKIE_NAME, default_timezone(context))

    def set_timezone_cookie(self, context, tz):
        if tz:
            cookie_path = "/" + api.portal.get().absolute_url(1)
            context.request.response.setCookie(TZ_COOKIE_NAME, tz, path=cookie_path)

    def id2class(self, cal, suffix=None):
        app_view = self.get_app_view()
        return app_view.id2class(cal, suffix=suffix)
