# -*- coding: utf-8 -*-
from __future__ import annotations

import datetime
import urllib.parse

import pydantic

from .base import ModelOut, Query


class SaveOut(ModelOut):
    key: str
    url: str
    title: str | None
    description: str | None
    last_processed_at: datetime.datetime | None
    is_netloc_banned: bool

    @property
    def parsed_url(self) -> urllib.parse.SplitResult:
        if hasattr(self, '_parsed_url') is False:
            self._parsed_url = urllib.parse.urlsplit(self.url)

        return self._parsed_url

    @property
    def parsed_url_query(self) -> dict:
        if hasattr(self, '_parsed_url_query') is False:
            self._parsed_url_query = urllib.parse.parse_qs(
                self.parsed_url.query,
            )

        return self._parsed_url_query

    @property
    def netloc(self) -> str:
        return self.parsed_url.netloc

    @property
    def is_youtube_video(self) -> bool:
        return any((
            all((
                self.netloc.endswith('youtube.com'),
                'v' in self.parsed_url_query,
            )),
            all((
                self.netloc.endswith('youtube.com'),
                self.parsed_url.path.startswith('/live'),
            )),
            self.netloc.endswith('youtu.be'),
        ))


class SaveIn(pydantic.BaseModel):
    url: str
    is_netloc_banned: bool | None = pydantic.Field(default=None)


class ImportedSaveIn(SaveIn):
    title: str


class SavesQuery(Query):
    pass
