import re
from collections.abc import Iterable, Iterator

from folkugat_web.dal.sql.temes import links as links_dal
from folkugat_web.model import temes as model

IMAGE_FORMATS_RE = "|".join([
    'jpg', 'jpeg', 'png'
])

LINK_RES = {
    model.LinkType.IMAGE: [
        re.compile(rf"^.*\.({IMAGE_FORMATS_RE})$")
    ],
    model.LinkType.PDF: [
        re.compile(r"^.*\.pdf$")
    ],
    model.LinkType.SPOTIFY: [
        re.compile(r"^.*spotify\.com.*$")
    ],
    model.LinkType.YOUTUBE: [
        re.compile(r"^.*youtube\.com.*$"),
        re.compile(r"^.*youtu\.be.*$"),
    ]
}


def guess_link_type(url: str) -> model.LinkType | None:
    for link_type, regexes in LINK_RES.items():
        for regex in regexes:
            if regex.match(url):
                return link_type
    return None


def add_links_to_tema(tema: model.Tema) -> model.Tema:
    if tema.id is not None:
        tema.links = list(links_dal.get_links(tema_id=tema.id))
    return tema


def add_links_to_temes(temes: Iterable[model.Tema]) -> Iterator[model.Tema]:
    return map(add_links_to_tema, temes)


def get_link_by_id(link_id: int, tema_id: int | None = None) -> model.Link | None:
    return next(iter(links_dal.get_links(link_id=link_id, tema_id=tema_id)), None)


def update_link(link: model.Link):
    links_dal.update_link(link=link)


def delete_link(link_id: int, tema_id: int | None = None):
    links_dal.delete_link(link_id=link_id, tema_id=tema_id)


def create_link(tema_id: int) -> model.Link:
    return links_dal.create_link(tema_id=tema_id)
