import os,sys , shutil
from contextlib import closing 

def capture_input(text, is_dir=None, int_range=None, default=None):
    ans = None
    
    while not ans:
        ans = raw_input(text).lower()
        if ans == '' and default is not None:
            return default
        
        elif int_range:
            try:
                _range = int_range[0] if len(int_range) == 1 else range(int_range[0], int_range[-1]+1)
                
                if int(ans) not in _range:
                    print '%s is not a valid option please enter a value %i - %i.' % (ans, int_range[0], int_range[-1])
                    ans = None
                else:
                    return int(ans)
                
            except ValueError:
                print '%s is not a valid option please enter a value %i - %i.' % (ans, int_range[0], int_range[-1])
                ans = None
        elif is_dir:
            if os.path.isdir(ans): return ans
            else: 
                print '%s is not a valid directory.' % ans
                ans = None
        elif ans:
            return ans
            
def get_project_name(projects, project_menu_items):
    project_menu_items.append('0: Exit')
    project = capture_input('Please select a previous project to use as the default business rules (project specific metadata and coding rules)\n' + '\n'.join(project_menu_items)+ '\n>>> ', int_range=(0,len(project_menu_items)-1))
    
    if project == 0:
        sys.exit()
    elif project == 10: 
        return False
    else:
        return projects[project-1]
    
if __name__ == '__main__':
    rules_dir = os.path.join(__file__, '..', '..', 'business_rules')
    src_dir = os.path.join(__file__, '..', '..', 'src')
    
    projects = [p for p in os.listdir(rules_dir)]
    project_name = False
    
    if not len(projects):
        print 'Bad build. No existing projects to use as defual business rules. Exiting.'
        print sys.exit()
            
    #capture user input
    while not project_name:
        if len(projects) <= 9:
            next = False
            project_name = get_project_name(projects, ['%i: %s' % (i+1, projects[i]) for i in xrange(0, len(projects))])
        else:
            project_name = get_project_name(projects, ['%i: %s' % (i+1, projects[i]) for i in xrange(9)] + ['10: more projects'])
            projects=projects[10:]

    root_dir = capture_input('Please enter the directory where project data will be stored\n>>> ', is_dir = True)
    db_host = capture_input('Please enter the database host (default=localhost)\n>>> ', default = 'localhost')
    db_port = capture_input('Please enter the database port (default=3306)\n>>> ', default = 3306, int_range=(0,9999999))
    
    #create base config file and default business rules
    if not os.path.isdir(os.path.join(src_dir, '..', 'build')):
        os.makedirs(os.path.join(src_dir, '..', 'build'))
    
    print 'Initializing Software...'
    print 'creating default business rules'
    for dir in ['metadata', 'rules']:
         
        dst = os.path.join(src_dir, '..', 'build', dir)
        if os.path.isdir(dst):
            print 'reinit: removing %s ' % dir
            shutil.rmtree(dst)
        print 'copying %s %s' % (project_name, dir)
        shutil.copytree(os.path.join(rules_dir, project_name, dir), dst)
    
    print 'create base config file'
    with closing(open(os.path.join(src_dir, 'bjs.config'), 'wb')) as file:
        out = ['[default]', 
               'root_dir=%s' % root_dir, 'follow_period=5', 'current_set=1', 'cores=2', 'transform_threads=100', 
               '[debug]',
               'verbose = False', 'halt_on_error = False', 'validate_regex_rules = True',
               '[db]',
               'host = %s' % db_host, 'port = %s' % db_port,
                ]
        
        file.write('\r\n'.join(out))

    print 'complete.'
        
        
        
        