import os
from datetime import datetime
from re import sub
from traceback import format_exc, extract_stack, format_list

import cardsharp as cs

from util import *
from ..configuration import segment_info, config
from ..util import set_LOOKUPS
from ..segment import Segment
from ..transform import *
from ..report import *

_segments = {}
for s in segment_info.itervalues():
    _segments[s['label']] = {'label': s['label'], 
                             'id': s['id'], 
                             'region_var': s['region_var'], 
                             'priority': s['priority']}

def run(**opt):
    try:
        segment = _segments[opt['segment']]
        del(opt['segment'])
        opt['segments'] = get_segments('process', **opt)

        #set the lookup table values
        #TODO add for only checking validation
        set_LOOKUPS()
        """Apply BJS processing rules."""
        opt['out_dir'] = os.path.join(opt['out_dir'], 'process')
        
        
        print "Starting %s processing at %s:" % (segment.get('label'), datetime.now().isoformat(' '))
        
        print "Begin data load and variable formatting..."
        
        s = Segment(segment.get('label'), 'process', **opt)
        s.validate_rules = opt['validate_rules']
        s.load_metadata_variables()
        #TODO add ability to load from processed database if already run
        s.load_staged_data()
        opt['variables'] = s.variables
        rules = get_rules(['0', '1', '2', '3', '4', '5'], segment, **opt)
        
        print "load and formatting complete."
        
        run_rules(['0', '1', '2', '3', '4', '5'], rules, s, s.name)
        
        cs.wait()
        
        #print "Saving and creating reports..."
        if opt['out_format'] != 'mysql':
            for format in (opt['out_format'], 'mysql'):
                s.options['out_format'] = format
                s.save()
        else:
            s.save()
            
        time = sub(':', '-', datetime.now().isoformat('_'))
        
        report = Report(s.review_path, **opt)
        report.create_reports()
        cs.wait()
        
        print "save complete at %s." % datetime.now().isoformat(' ')
        return 1
    except:
        
        if opt['verbose']:
            raise
        return (opt['log_dir'], format_exc(), format_list(extract_stack()))