import json
import os
import glob
from sanitize_filename import sanitize

db = []

# year/submitter/title

with open('index.json', 'r', encoding='utf-8') as infile:
	db = json.load(infile)
print('Loaded index.json')

print('This script will find & rearrange all the files in userart.')
print('Please enter the desired folder structure: (ex: {year}/{page} - {submitter} - {title}; you can also use {date})')
print('If you leave it blank, all the images will go into userart on the same level.')
structure = input()
#if len(structure) < 1:
#    structure = "{year}/{submitter}/{title}"

print('Globbing')
files = glob.glob('userart/**/*', recursive=True)
print("Moving files, this will take a long and unspecified amount of time.. (maybe five minutes)")

for file in files:
    basename = os.path.basename(file)
    for e in db:
        if e['file'] == basename:
            dirr = 'userart/' + structure.replace("{year}", e['date'][0:4]).replace("{submitter}", e['submitter']).replace('{title}', sanitize(e['title'])).replace("{date}", e['date']).replace('{page}', str(e['page']))
            newname = dirr + '/{0}'.format(basename)
            try:
                os.makedirs(dirr)
            except:
                pass
            os.rename(file, newname)

print('Cleaning up empty folders (this may take a while to go through and find any, you may quit if desired)')

def remove_empty_dir(path):
    try:
        os.rmdir(path)
        print('[X] {0}'.format(path))
    except OSError:
        pass

def remove_empty_dirs(path):
    for root, dirnames, filenames in os.walk(path, topdown=False):
        for dirname in dirnames:
            remove_empty_dir(os.path.realpath(os.path.join(root, dirname)))
# https://stackoverflow.com/a/23488980

remove_empty_dirs('userart/')

print('Done!')
