#!/bin/python3

# external modules

from os import path, system, walk
from pathlib import Path
from sys import argv


# utility functions

def scan_source():
    _artist_dirs, _album_dirs, _full_paths = [], [], []
    for _root, _directories, _files in walk(path.expanduser(source)):
        for _dir in sorted(_directories):
            if not _root.endswith(path.expanduser(source)):
                _artist_dirs.append(_root)
    _artist_dirs = list(set(_artist_dirs))
    for _artist in sorted(_artist_dirs):
        for _root, _directories, _files in walk(path.expanduser(_artist)):
            if not _root.endswith(path.expanduser(_artist)):
                _album_dirs.append(_root)
    _album_dirs = list(set(_album_dirs))
    for _album in sorted(_album_dirs):
        for _root, _directories, _files in walk(path.expanduser(_album)):
            for _filename in _files:
                if _filename.endswith('.flac'):
                    _full_paths.append(f"{_album}/{_filename[:-5]}")
    return _album_dirs, _full_paths


def create_destination():
    for _dir in source_directories[0]:
        Path(path.expanduser(_dir.replace(path.expanduser(source), path.expanduser(destination))))\
            .mkdir(0o700, parents=True, exist_ok=True)


def scan_destination_convert_alac():
    for _file in source_directories[1]:
        if not Path(f"{_file.replace(path.expanduser(source), path.expanduser(destination))}.m4a").is_file():
            system(f"ffmpeg -i '{_file}.flac' -c:v copy -c:a alac -map_metadata 0 -id3v2_version 3 "
                   f"'{_file.replace(path.expanduser(source), path.expanduser(destination))}.m4a'")


def scan_destination_convert_mp3():
    for _file in source_directories[1]:
        print(_file)
        if not Path(f"{_file.replace(path.expanduser(source), path.expanduser(destination))}.mp3").is_file():
            system(f"ffmpeg -i '{_file}.flac' -c:v copy -ab 320k -map_metadata 0 -id3v2_version 3 "
                   f"'{_file.replace(path.expanduser(source), path.expanduser(destination))}.mp3'")


def rg2sc():
    if argument.__contains__('-f'):
        system(f"{rg2sc} -f {destination}")
    else:
        system(f"{rg2sc} {destination}")


# program start sequence

# retrieve typed argument
argument_list = argv
i, argument = 0, ''
for _ in argument_list:
    while i < len(argument_list) - 1:
        i += 1
        argument += argument_list[i] + ' '
argument = argument[:-1]

source = input('Source parent directory: ')
if source.endswith('/'):
    source = source[:-1]
destination = input('Destination parent directory: ')
if destination.endswith('/'):
    destination = destination[:-1]

source_directories = scan_source()
create_destination()
if argument.__contains__('--alac'):
    scan_destination_convert_alac()
else:
    scan_destination_convert_mp3()
    rg2sc()
