from os import listdir, makedirs, remove
from os.path import abspath, dirname, join, sep
from shutil import rmtree
from urllib.request import urlretrieve

from django.conf import settings

from owltail.api_handler import APIHandler

BASE_DIR = dirname(abspath(__file__))


default_api_handler = APIHandler()


class SongsSynchroniser:
    def __init__(self, api_handler=default_api_handler, *args, **kwargs):
        self.api_handler = api_handler
        self.songs_folder = kwargs.get(
            'songs_folder', settings.DEFAULT_SONGS_FOLDER
        )

    def start(self):
        previous_themes = listdir(settings.DEFAULT_SONGS_FOLDER)
        print(previous_themes)
        themes = self.api_handler.get_themes()
        current_themes = []

        # create new folder and synchronise_songs
        for theme in themes:
            name = theme['name']
            current_themes.append(name)
            theme_folder = join(self.songs_folder, name)
            makedirs(theme_folder, exist_ok=True)
            self.synchronise_songs(theme_folder, theme['songs'])

        # delete old folders
        for previous_theme in previous_themes:
            if previous_theme not in current_themes:
                rmtree(join(settings.DEFAULT_SONGS_FOLDER, previous_theme))

    def synchronise_songs(self, theme_folder, songs):
        filenames = [self.extract_filename(song['url']) for song in songs]
        for existing_file in listdir(theme_folder):
            if existing_file not in filenames:
                remove(join(theme_folder, existing_file))

        for song in songs:
            full_filename = join(
                theme_folder, self.extract_filename(song['url'])
            )
            urlretrieve(song['url'], full_filename)

    def extract_filename(self, url):
        bits = url.split(sep)
        return bits[-1]
