import calendar
import time
from datetime import datetime

import pytz

from core.chat_blob import ChatBlob
from core.command_param_types import Any, Const
from core.decorators import instance, command


@instance()
class TimeController:
    def __init__(self):
        self.time_format = "%Y-%m-%d %H:%M:%S %Z%z"

    @command(command="time", params=[Const('all', is_optional=True)], access_level="member",
             description="Show the current time in every timezone")
    def time_cmd(self, _, const_all):
        if const_all:
            blob = "Unixtime => %d\n\n" % int(time.time())
            current_region = ""
            dt = datetime.now()
            for tz in pytz.common_timezones:
                result = tz.split("/", 2)
                if len(result) == 2:
                    region, city = result
                else:
                    region = result[0]
                    city = result[0]

                if current_region != region:
                    blob += "\n<pagebreak><header2>%s</header2>\n" % region
                    current_region = region

                blob += "%s => %s\n" % (city, dt.astimezone(pytz.timezone(tz)).strftime(self.time_format))

            return ChatBlob("Timezones", blob)
        else:
            now = datetime.utcnow()
            day = f"{now.day}"
            if now.day == 1:
                day += "st"
            elif now.day == 2:
                day += "nd"
            elif now.day == 3:
                day += "rd"
            else:
                day += "th"
            return f"Currently its {now.hour:02}:{now.minute:02}:{now.second:02} " \
                   f"{calendar.month_name[now.month]} {day}, {now.year + 27474} Rubi-Ka Universal Time."

    @command(command="time", params=[Any("timezone")], access_level="member",
             description="Show time for the specified timezone")
    def time_zone_cmd(self, _, timezone_str):
        timezone_str = timezone_str.lower()
        for tz in pytz.common_timezones:
            if tz.lower() == timezone_str:
                return f"{tz} => {datetime.now(tz=pytz.timezone(tz)).strftime(self.time_format)}"

        return "Unknown timezone."
