# -*- coding: utf-8 -*-
"""Optional Home display savings; normal mode preserves counts and artwork.

The service publishes enabled() as 'true'/'false' in Home's milionar.low_power
property at startup and on settings changes. Widget builders apply limit()
before constructing items and artwork() before setting their art.
"""
import re

import xbmcaddon

_TMDB = re.compile(r'^(https?://image\.tmdb\.org/t/p/)(w500|w780|w1280)(/.*)$')
_TMDB_SIZES = {'w500': 'w342', 'w780': 'w300', 'w1280': 'w300'}
_VINYL = re.compile(
    r'^(https://hosting\.pilsfree\.net/chudy/proxy/4017/api/vinyl/'
    r'(?:cover/\d+|playlists/\d+/cover|browse/albums/[^/?#|]+/cover|browse/artists/cover)\?)'
    r'([^#|]*)(.*)$')


def enabled():
    return xbmcaddon.Addon('plugin.video.milionar').getSetting('skin_low_power') == 'true'


def limit(value):
    """Cap an already resolved numeric row limit only in the optional profile."""
    return min(value, 10) if enabled() else value


def artwork(url):
    """Reduce known widget image sizes, preserving query, version and Kodi headers."""
    if not url or not enabled():
        return url
    match = _TMDB.match(url)
    if match:
        return match[1] + _TMDB_SIZES[match[2]] + match[3]
    match = _VINYL.match(url)
    if match:
        query = re.sub(r'(^|&)size=600(?=&|$)', r'\g<1>size=300', match[2])
        return match[1] + query + match[3]
    return url
