import logging
from decimal import Decimal
from itertools import takewhile
from typing import Optional

from smb.common.http_client import BaseHttpClientException

from maps_adv.common.ugcdb_client import OrderBy, UgcdbClient


class RatingProvider:
    def __init__(self, permalink: int, ugcdb_client: UgcdbClient):
        self._permalink = permalink
        self._ugcdb_client = ugcdb_client

    async def fetch_rating(
        self, reviews_min_rating: Optional[int] = None
    ) -> Optional[dict]:
        order_by = OrderBy.BY_RATING_DESC if reviews_min_rating else OrderBy.BY_TIME
        try:
            got = await self._ugcdb_client.fetch_org_reviews(
                permalink=self._permalink, limit=10, order_by=order_by
            )
        except BaseHttpClientException as exc:
            logging.getLogger(__name__).exception(
                f"Failed to get rating for permalink {self._permalink}", exc_info=exc
            )
            return None

        if got is None:
            return None

        got["reviews"] = list(filter(lambda r: "username" in r, got["reviews"]))
        if reviews_min_rating is not None:
            got["reviews"] = list(
                takewhile(lambda r: r["rating"] >= reviews_min_rating, got["reviews"])
            )

        for review in got["reviews"]:
            review["rating"] = Decimal(review["rating"])
            review["created_at"] = review.pop("updated_at")
            if "avatar" in review:
                review["userpic"] = review.pop("avatar")

        return got
