"""
Utilities for general purposes. Meant to be imported from other packages
and have no dependencies of other packages
"""

from Acquisition import aq_chain
from logging import getLogger
from plone.base.utils import is_truthy
from ploneintranet.layout.app import IAppsContainer
from urllib.parse import parse_qs
from urllib.parse import urlparse

import os

logger = getLogger(__name__)

# Determine the test site marker from the environment variable.
# If the variable is not set, or set to a false value, no marker is used.
# If set to a true-like value, the marker "test" is used.
# If set to any other value, that value is used as the marker.
TEST_SITE_MARKER = os.environ.get("TEST_SITE_MARKER", "")
if TEST_SITE_MARKER.lower() in ("0", "false", "no", "off"):
    TEST_SITE_MARKER = ""
elif is_truthy(TEST_SITE_MARKER):
    TEST_SITE_MARKER = "test"


def shorten(text, length=20, ellipsis="\u2026"):
    if len(text) <= length:
        return text
    if " " not in text:
        return f"{text[: length - 4]} {ellipsis}"
    return " ".join(text[:length].split(" ")[:-1] + [ellipsis])


def parent_container(context):
    if IAppsContainer.providedBy(context):
        return context
    context = getattr(context, "context", context)
    for parent in aq_chain(context):
        if IAppsContainer.providedBy(parent):
            return parent


def in_app(context):
    return IAppsContainer.providedBy(parent_container(context))


def youtube_url(url, youtube_url_template="https://www.youtube-nocookie.com/embed/{v}"):
    """Try to sniff the youtube URL video id and to create a proper url for it"""
    parsed_url = urlparse(url)
    v = next(
        iter(parse_qs(parsed_url.query).get("v", [])), ""
    ) or parsed_url.path.lstrip("/")
    return youtube_url_template.format(v=v)
