"""The company's own logo (uploaded in Company settings) for letterheads, invoices and exports."""
import os
import secrets

from flask import current_app

from .i18n import t
from .ledger import AccountingError

ALLOWED = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}
MAX_BYTES = 2 * 1024 * 1024
PRODUCT_LOGO = os.path.join(os.path.dirname(__file__), "static", "brand", "vertex-logo.png")


def folder():
    path = os.path.join(os.path.dirname(current_app.config["DATABASE"]), "uploads", "logo")
    os.makedirs(path, exist_ok=True)
    return path


def logo_path(company):
    """Absolute path of the company logo, or None."""
    name = company["logo"] if company and "logo" in company.keys() else None
    if not name:
        return None
    path = os.path.join(folder(), os.path.basename(name))
    return path if os.path.exists(path) else None


def save_logo(file):
    """Store an uploaded logo (PNG or JPG, at most 2 MB), trimmed and resized; returns the stored file name."""
    from PIL import Image
    ext = os.path.splitext(file.filename or "")[1].lower()
    if ext not in ALLOWED:
        raise AccountingError(t("The logo must be a PNG or JPG image."))
    data = file.read()
    if len(data) > MAX_BYTES:
        raise AccountingError(t("The logo is larger than 2 MB."))
    import io
    try:
        im = Image.open(io.BytesIO(data))
        im.load()
    except Exception:
        raise AccountingError(t("The file is not a readable image."))
    im = im.convert("RGBA")
    box = im.getbbox()
    if box:
        im = im.crop(box)
    im.thumbnail((1200, 400))
    name = f"logo-{secrets.token_hex(6)}.png"
    im.save(os.path.join(folder(), name))
    return name


def remove_logo(name):
    if name:
        path = os.path.join(folder(), os.path.basename(name))
        if os.path.exists(path):
            os.remove(path)
