#!/usr/bin/env python
from zoneinfo import ZoneInfo

import flask
from dateutil.parser import parse
from flask_assets import Bundle, Environment
from logzero import logger, setup_logger
from webassets.filter import get_filter

from config import cfg
from apis import calendar as gcal


setup_logger(name=__name__)

app = flask.Flask(__name__)
libsass = get_filter(
    "libsass",
    as_output=True,
    style="compressed",
)
assets = Environment(app)  # create an Environment instance
bundles = {  # define nested Bundle
    "style": Bundle(
        "scss/*.scss",
        filters=(libsass),
        output="style.css",
    )
}
assets.register(bundles)


@app.route("/")
def events():
    return flask.render_template(
        "index.html",
        calendar=gcal.load_calendar(
            service=gcal.build_service(),
            calendar_id=cfg.calendar_id,
        ),
    )


@app.template_filter()
def parse_tz_datetime(datetime_str):
    return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config["display_timezone"]))


@app.template_filter()
def replace_tz(datetime_obj):
    return datetime_obj.replace(tzinfo=ZoneInfo(app.config["display_timezone"]))


@app.template_filter()
def hex2rgb(hex, alpha=None):
    """Convert a string to all caps."""
    if not hex.startswith("#"):
        return hex
    h = hex.lstrip("#")
    try:
        rgb = tuple(int(h[i : i + 2], 16) for i in (0, 2, 4))  # noqa
    except Exception as err:
        logger.exception(f"unable to convert {hex=} to rgb: {err}")
        return h
    if alpha is None:
        return f"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})"
    else:
        return f"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})"


def get_base_url():
    if prefix := cfg.gcs_bucket_prefix:
        return f"https://{cfg.hostname}/{prefix}"
    return f"https://{cfg.hostname}"


def create_app():
    cfg.load()

    # TODO: do this default settings thing better?
    default_app_config = dict(
        display_timezone=cfg.display_timezone,
        FREEZER_BASE_URL=get_base_url(),
        FREEZER_STATIC_IGNORE=["*.scss", ".webassets-cache/*", ".DS_Store"],
        FREEZER_RELATIVE_URLS=False,
        FREEZER_REMOVE_EXTRA_FILES=True,
    )
    logger.info(f"create_app() => {default_app_config=}")
    app.config.update(default_app_config)
    return app


if __name__ == "__main__":
    app = create_app()
    app.run(
        host="0.0.0.0",
        debug=True,
    )

[((14, 0, 14, 27), 'logzero.setup_logger', 'setup_logger', (), '', False, 'from logzero import logger, setup_logger\n'), ((16, 6, 16, 27), 'flask.Flask', 'flask.Flask', ({(16, 18, 16, 26): '__name__'}, {}), '(__name__)', False, 'import flask\n'), ((17, 10, 21, 1), 'webassets.filter.get_filter', 'get_filter', (), '', False, 'from webassets.filter import get_filter\n'), ((22, 9, 22, 25), 'flask_assets.Environment', 'Environment', ({(22, 21, 22, 24): 'app'}, {}), '(app)', False, 'from flask_assets import Bundle, Environment\n'), ((24, 13, 28, 5), 'flask_assets.Bundle', 'Bundle', (), '', False, 'from flask_assets import Bundle, Environment\n'), ((78, 4, 78, 14), 'config.cfg.load', 'cfg.load', ({}, {}), '()', False, 'from config import cfg\n'), ((88, 4, 88, 57), 'logzero.logger.info', 'logger.info', ({(88, 16, 88, 56): 'f"""create_app() => default_app_config={default_app_config!r}"""'}, {}), "(f'create_app() => default_app_config={default_app_config!r}')", False, 'from logzero import logger, setup_logger\n'), ((46, 11, 46, 30), 'dateutil.parser.parse', 'parse', ({(46, 17, 46, 29): 'datetime_str'}, {}), '(datetime_str)', False, 'from dateutil.parser import parse\n'), ((46, 46, 46, 86), 'zoneinfo.ZoneInfo', 'ZoneInfo', ({(46, 55, 46, 85): "app.config['display_timezone']"}, {}), "(app.config['display_timezone'])", False, 'from zoneinfo import ZoneInfo\n'), ((51, 39, 51, 79), 'zoneinfo.ZoneInfo', 'ZoneInfo', ({(51, 48, 51, 78): "app.config['display_timezone']"}, {}), "(app.config['display_timezone'])", False, 'from zoneinfo import ZoneInfo\n'), ((63, 8, 63, 67), 'logzero.logger.exception', 'logger.exception', ({(63, 25, 63, 66): 'f"""unable to convert hex={hex!r} to rgb: {err}"""'}, {}), "(f'unable to convert hex={hex!r} to rgb: {err}')", False, 'from logzero import logger, setup_logger\n'), ((38, 20, 38, 40), 'apis.calendar.build_service', 'gcal.build_service', ({}, {}), '()', True, 'from apis import calendar as gcal\n')]