import requests
import os
from PIL import Image
from io import BytesIO

from common import *


def save_image_from_url(url, name, image_dir="playlist_covers"):
    response = requests.get(url)

    if response.status_code != 200:
        raise "Cannot fetch the playlist cover"

    image = Image.open(BytesIO(response.content))

    directory = os.path.join(data_dir, image_dir)
    os.makedirs(directory, exist_ok=True)
    file_path = os.path.join(directory, f"{name}.jpg")
    print(f"Image saved {file_path}")
    image.save(file_path)


def load_playlist_covers():
    playlists = get_data('playlists')

    for pl in playlists:
        if len(pl['images']):
            url = pl['images'][0]['url']
            save_image_from_url(url, pl['name'])


def load_user_cover():
    user_data = get_data("user_data")
    url = user_data['images'][1]['url']
    save_image_from_url(url, "user", ".")


def load():
    load_user_cover()
    load_playlist_covers()


if __name__ == "__main__":
    load()
