# LOADERuj
#
# Skrypt do ukladania archiwum gier :)
# by mgr inz. Rafal

from fnmatch import fnmatch
from collections import defaultdict
import os, os.path
import operator
import shutil
import glob


# -- Tutaj sobie edytujemy
rootPath = '/Volumes/Macintosh HD/Users/Administrator/test_loaderuj'
per_dir = 200
# ------------------------


targetPath = rootPath + '/_'
atrMask = '*.atr'
xexMask = '*.xex'

fls = list()
target_tree = defaultdict(list)
cleanup_list = list()

class dir_entry(object):
    def __init__(self, file_name, directory):
        self.file_name = file_name
        self.directory = directory

def number_for_suffix(suf):
    if suf < 10:
        return '_0'+`suf`
    return '_'+`suf`

def macz(pattern, dir, files):
    global fls
    for filename in files:
        if fnmatch(filename, pattern):
            fls.append(dir_entry(filename, dir))

def makedir(name):
    try: 
        os.makedirs(name)
    except OSError:
        if not os.path.isdir(name):
            raise

def mess_up(target_dir, mask):
    global fls
    global target_tree
    fls[:]=[]
    target_tree.clear()
    print 'Scanning dir...'
    os.path.walk(rootPath, macz, mask)
    print len(fls),'files found'
    if len(fls) < 2:
        print 'No need to process'
        exit
    print 'Sorting...'
    fls = sorted(fls, key=operator.attrgetter('file_name'))
    print 'Creating target dir...'
    if os.path.exists(target_dir):
        print target_dir,' dir already exists. Remove it first.'
        exit
    makedir(target_dir)
    print 'Moving files around...'
    for entry in fls:
        letter = entry.file_name[:1].upper()
        target_tree[letter].append(entry)
    for dst in target_tree:
        cleanup_list[:] = []
        to_be_created = target_dir + '/' + dst
        makedir(to_be_created)
        counter = 0
        first = 1
        suffix=1
        for fl in target_tree[dst]:
            if first == 1:
                cleanup_list.append(fl.directory+'/'+fl.file_name)
            shutil.copy(fl.directory+'/'+fl.file_name,to_be_created)
            counter+=1
            if counter == per_dir:
                counter = 0
                if first:
                    to_be_created += '/'
                    to_be_created += dst
                    to_be_created += number_for_suffix(suffix)
                    first = 0
                else:
                    to_be_created = to_be_created[:-5]
                    suffix+=1        
                    to_be_created += '/'
                    to_be_created += dst
                    to_be_created += number_for_suffix(suffix)
                makedir(to_be_created)
        if first <> 1:
            final_cleanup = target_dir + '/' + dst
            final_cleanup_dir = final_cleanup + '/' + dst + '_00/'
            makedir(final_cleanup_dir)
            for path in glob.iglob(final_cleanup+'/*.*'):
                shutil.move(path, final_cleanup_dir)

print '*** Processing ATRs ***'
mess_up(targetPath+'atr', atrMask)

print
print '*** Processing XEXs ***'
mess_up(targetPath+'xex', xexMask)

