#! /usr/bin/env python

from abjad.cfg.cfg import ABJADPATH
from abjad.tools import clear_terminal
import os
import pprint
import re


def _capitalize_test_file_names( ):
   uncapitalized_pattern = re.compile(r'test_[a-z]+.+py$')
   total_test_files = 0
   old, new = 'zzz', 'zzz'
   for path, subdirectories, files in os.walk(ABJADPATH):
      for f in files:
         if uncapitalized_pattern.match(f) or f.endswith('_tmp.py'):
            if not 'tools' in f and not 'debug' in f and not 'lily_voice' in f and not 'iterate' in f:
               full_file_name = os.path.join(path, f)
               old, new = _rename_test_file(f, full_file_name, old, new)
               total_test_files += 1
   print ''

def _rename_test_file(short_file_name, full_file_name, old, new):
   print full_file_name
   if old in short_file_name:
      use_previous = raw_input('Replace %s with %s? ' % (old, new))
   if short_file_name.endswith('_tmp.py'):
      old = '_tmp.py'
      new = '.py'
   elif old not in short_file_name or use_previous.lower( ) != 'y':
      old = raw_input('Old text: ')
      new =  raw_input('New text: ')
   if old.lower( ) == new.lower( ):
      new_short_file_name = short_file_name.replace(old, new)
      new_short_file_name = new_short_file_name.replace('.py', '_tmp.py')
      new_full_file_name = full_file_name.replace(short_file_name, new_short_file_name)
      first_command = 'svn mv %s %s' % (full_file_name, new_full_file_name)
      #print first_command
      os.system(first_command)
      #revised_new_full_file_name = new_full_file_name.replace('_tmp.py', '.py')
      #second_command = 'svn mv %s %s' % (new_full_file_name, revised_new_full_file_name)
      ###print second_comand
      #os.system(second_command)
   else:
      new_short_file_name = short_file_name.replace(old, new)
      new_full_file_name = full_file_name.replace(short_file_name, new_short_file_name)
      command = 'svn mv %s %s' % (full_file_name, new_full_file_name)
      #print command
      os.system(command)
   print ''
   print ''
   return old, new
      
   
if __name__ == '__main__':
   iotools.clear_terminal( )
   print 'Finding test files ...'
   print ''
   _capitalize_test_file_names( )
