#!/usr/bin/env python3

# Normalisation is done at the default of each program,
# which is usually -89.0 dB

import os
import coloredlogs
import logging
import r128gain
import sys

coloredlogs.install(level='DEBUG', fmt='%(levelname)s %(message)s')
log = logging.getLogger()

# TODO Remove debug

# Constants
FORCE = '-f' in sys.argv
if FORCE:
    sys.argv.remove('-f')
SOURCE_FOLDER = os.path.realpath(sys.argv[1]) if len(sys.argv) >= 2 else os.path.join(os.path.expanduser("~"), "Musiques")

def isMusic(f):
    ext = os.path.splitext(f)[1][1:].lower()
    return ext in r128gain.AUDIO_EXTENSIONS

# Get album paths
log.info("Listing albums and tracks")
albums = set()
singleFiles = set()
for root, dirs, files in os.walk(SOURCE_FOLDER):

    relRoot = os.path.relpath(root, SOURCE_FOLDER)

    head, tail = os.path.split(relRoot)
    # 1 component in the path: save files path as single
    if not len(head):
        for f in files:
            if isMusic(f):
                fullPath = os.path.join(root, f)
                singleFiles.add(fullPath)
    head, tail = os.path.split(head)
    if len(head):
        continue
    # 2 components in the path: save album path
    albums.add(root)

log.info("Processing single files")
# r128gain.process(list(singleFiles), album_gain=False, skip_tagged=not FORCE, report=True)
for album in albums:
    albumName = os.path.relpath(album, SOURCE_FOLDER)
    log.info("Processing album {}".format(albumName))

    musicFiles = set()
    for root, dirs, files in os.walk(album):
        for f in files:
            if isMusic(f):
                fullPath = os.path.join(root, f)
                musicFiles.add(fullPath)

    # print(musicFiles)
    if not len(musicFiles):
        continue
    r128gain.process(list(musicFiles), album_gain=True, skip_tagged=not FORCE, report=True)
    print("==============================")