from traceback import format_exc, extract_stack, format_list
from datetime import datetime
import cardsharp as cs

from util import get_segments
from ..segment import Segment,segment_info

_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)
        
        s = Segment(segment.get('label'), 'convert', **opt)
        #need to set variable length if we convert before running stage
        if opt['original']:
            s.load_metadata_variables()
            s.load_data()
            s.convert_vars()
            if opt['in_format'] == 'spss' and opt['out_format'] == 'del':
                x=1
            else:
                s.get_rules()
                s.set_rules()
        else:
            s.load_metadata_variables()
            s.load_staged_data()
        s.save()
        cs.wait()
        return 1
        print 'Dataset(s) converted at %s' % datetime.now().isoformat(' ')
    except:
        if opt['verbose']:
            raise
        return (opt['log_dir'], format_exc(), format_list(extract_stack()))