import requests
import warnings


class Api:
    def __init__(self, refresh_token: str, base_64: str):
        self.refresh_token = refresh_token
        self.base_64 = base_64
        self.access_token = None
        self.header = None

    def refreshAuth(self) -> None:
        uri = "https://accounts.spotify.com/api/token"
        data = {
            "grant_type": "refresh_token",
            "refresh_token": self.refresh_token,
        }
        req = requests.post(
            uri, data=data, headers={"Authorization": "Basic " + self.base_64}
        ).json()
        self.access_token = req["access_token"]
        self.header = {"Authorization": f"Bearer {self.access_token}"}
        return req["expires_in"]

    def getPlaying(self):
        url = "https://api.spotify.com/v1/me/player/currently-playing"
        req = requests.get(url, headers=self.header)
        if req.status_code == 204:
            return "not-playing"
        if req.status_code != 200:
            warnings.warn(f"Unknown API Error {req.status_code},\n{req.content}")
            return None
        return self._format_req(req.json())

    def _format_req(self, r):
        item, album = r["item"], r["item"]["album"]
        res = {
            "progress_ms": r["progress_ms"],
            "duration_ms": item["duration_ms"],
            "track": item["name"],
            "album": album["name"],
            "artists": [artist["name"] for artist in item["artists"]],
            "img_url": None,
        }
        img_urls = album.get("images", [])
        if img_urls:
            res["img_url"] = img_urls.pop()["url"]
        else:
            warnings.warn(
                f"{res['track']} - {res['artists']}\nAlbum art can't be found\n{img_urls}"
            )
        return res
