'''
***   Ki Renamer   ***

usage: kir <filter> <rule> [-p] [-r]

<filter>          Regex - Filter the files to rename
<rule>            Renaming rule

Options:
  --version               Displays the current version of Ki Renamer
  -h, --help              Show usage and options
  -p, --preview           Print more informations
  -r, --recursive         Also rename files in sub-directories recursively

Use a regular expression to select the files to rename in the working directory;
'''
import os
import re

from docopt import docopt

__VERSION__ = "0.1"

# args = docopt(__doc__, version=__VERSION__, options_first=False)

### for debugging purpose
preview = True
working_dir = r".\test"
kir_filter = "^(.*)(?i:File)(.*)$"
kir_rule = "\\1abc\\2"
recursive = False
###

### future
# preview = args["--preview"]
# recursive = args["--recursive"]
# kir_filter = args["<filter>"]
# kir_rule = args["<rule>"]
# working_dir = os.getcwd()
###

def _ren(old_name, new_name):
    if preview:
        print("{} > {}".format(old_name, new_name))
    else:
        return os.rename( os.path.join(working_dir, old_name), 
                          os.path.join(working_dir, new_name) )


if __name__ == '__main__':
    
    regex = re.compile( kir_filter )

    # build the 'to be renamed' list
    to_rename = []
    files_count = 0
    for root, dirs, files in os.walk(working_dir, onerror=None, followlinks=False):
        for name in files:
            files_count += 1
            new_name = regex.sub(kir_rule, name)
            if name != new_name :
                to_rename.append( (name, new_name ) )
        for name in dirs:
            pass
        if not recursive:
            break
    
    # control the result
    print("{}/{} Files to rename".format( len(to_rename), files_count))
    
    # apply rename (or preview operation)
    for filename, newname in to_rename: 
        _ren(filename, newname)
    
    print("> done")

