import os, shutil
from contextlib import closing
import md5

def run(**opt):
    """Initializes a new project"""
    
    out = ["[default]"]
    #create the config file
    out.append('root_dir = %s' % opt['root_dir'])
    out.append('project_dir = %s' % os.path.join(opt['root_dir'], 'project_data', opt['name']))
    
    for o in [('in_dir', 'input'), ('out_dir', 'output'), 
              ('tmp_out_dir', 'tmp'), ('log_dir', 'output\log'),
              ('output\report_dir', 'report'), ('review_dir', 'output\\review'),  
              ('meta_dir', 'metadata'), ('rule_dir', 'rules'), 
              ('offense_dir', 'rules\process_rules_2'),
              ('admrec_dir', 'rules\process_rules_3'), 
              ('xwalk_out_dir', 'output\crosswalks'), 
              ('stable_dir', 'output\stable'),
              ('predict_dir', 'predict')]:
        
        #create the config option
        path = os.path.join(opt['root_dir'], 'project_data', opt['name'], o[1])
        out.append('%s = %s' % (o[0], os.path.normpath(path)))
        
        #copy the base rules and metadata
        if o[0] in ['rule_dir', 'meta_dir']:    
            if o[0] == 'rule_dir':
                sub_dir = 'rules'
            elif o[0] == 'predict_dir':
                sub_dir = 'predict'
            else:
                sub_dir = 'metadata'
                 
            r = opt[o[0]] if opt[o[0]] else os.path.join(__file__,'..','..','..','build',sub_dir)
            
            shutil.copytree(os.path.join(r), path)
        else:
            #create the directory
            path = os.path.join(path, 'set_1' if o[0] == 'review_dir' else '')
            if not os.path.isdir(path):
                os.makedirs(path)
                
    if int(opt['threads']) > 250:
        print 'Exceeded max threads, decreasing to 250.'
        opt['threads'] = 250
        
    #finish up the defaul section
    out.extend(['follow_period = 5',
                'current_set = 1', 
                'cores = %s' % opt['cores'],
                'transform_threads = %s\r\n' % opt['threads']])
    
    #add the security section
    out.extend(['[security]', 'HMAC_KEY= %s' % md5.new().hexdigest()])
    
    #add the debug section
    out.extend(['[debug]', 
                'verbose = %s' % opt['verbose'], 
                'halt_on_error = False', 
                'validate_regex_rules = True\r\n'])
    
    #add the database section
    out.extend(['[db]', 
                'host = %s' % opt['host'], 
                'port = %s\r\n' % opt['port']])

    #add the standardized database section
    out.extend(['[db_stand]',
                'name = %s' % opt['db_stand_name'],
                'user = %s' % opt['db_stand_user'],
                'pass = %s' % opt['db_stand_pass'],
                'collate = utf8_unicode_ci',
                'encoding = utf8\r\n'])
    
    #add the recidivism database section
    out.extend(['[db_recid]',
                'name = %s' % opt['db_recid_name'],
                'user = %s' % opt['db_recid_user'],
                'pass = %s' % opt['db_recid_pass'],
                'collate = utf8_unicode_ci',
                'encoding = utf8\r\n'])
    
    #create the segment config options
    #add subject section
    out.extend(['[segment_subject]',
                'id = 1',
                'label = subject',
                'region_var = rapstatex',
                'priority = 1\r\n'])
    
    #add arrest section
    out.extend(['[segment_arrest]',
                'id = 2',
                'label = arrest',
                'region_var = rapstatex',
                'priority = 2\r\n'])
    
    #add sentence section
    out.extend(['[segment_sentence]',
                'id = 3',
                'label = sentence',
                'region_var = rapstatex',
                'priority = 3\r\n'])
    
    #add prosecution section
    out.extend(['[segment_prosecution]',
                'id = 4',
                'label = prosecution',
                'region_var = rapstatex',
                'priority = 5'])

    #add supervision section
    out.extend(['[segment_supervision]',
                'id = 5',
                'label = supervision',
                'region_var = rapstatex',
                'priority = 4\r\n'])
    
    #add supervision section
    out.extend(['[segment_demographic]',
                'id = 6',
                'label = demographic',
                'region_var = rapstatex',
                'priority = 6'])


    
    #write the config file
    out_path1=os.path.normpath(os.path.join(opt['root_dir'],'project_data', 
                                           opt['name'], '%s.config'%opt['name']))
    with closing(open(out_path1, 'wb')) as file:
        file.write('\r\n'.join(out))
    
    #set this as the current project
    out_path2 = os.path.join(__file__, '..','..', '..', 'project_data', 'current_project.txt')    
    with closing(open(out_path2, 'wb')) as file:
        file.write('%s' % out_path1)