import sys
from os.path import normpath, join
from datetime import datetime

import cardsharp as cs

from util import *
from ..util import *
from ..configuration import db_info, config

def convert(cmd): 
    args = cmd.args
    _log = normpath(join(config.log_dir, 'set_%i' % config.current_set, 'convert'))
    opt = {'in_dir': check_file(args.in_dir, as_dir = True),
           'out_dir': check_file(args.out_dir, as_dir = True),
           'meta_dir': check_file(args.metadata_dir, as_dir = True),
           'in_format': check_format(args.in_format),
           'out_format': check_format(args.out_format),
           'in_delimiter': args.in_delimiter,
           'out_delimiter': args.out_delimiter,
           'max_string_width': args.max_width,
           'verbose': args.verbose,
           'original': args.original,
           'db_info': db_info['stand'],
           'log_dir': create_log_dir(_log, replace=True)
        }
    
    cs.config.debug = True if args.verbose else False
    
    if args.out_format == args.in_format:    
        print "in_format: %s and out_format: %s can not be the same." % (args.in_format, 
                                                                         args.out_format)
        sys.exit(1)
    
#    if args.out_format in ['text', 'csv', 'del'] and args.original == True:    
#        print "Can not save original data to text or csv to prevent possible invalid loading."
#        sys.exit(1)
    
    if args.in_format == 'excel':
        print "Can not convert segment data from excel due to integer loading errors."
        sys.exit(1)
        
    print "Converting data..."
    
    _segments = [segment_run_map[seg] for seg in cmd.args.segments.split('|')]
    
    for segment in _segments:
        __opt = opt.copy()
        
        if segment == 'subject':
            continue
        
        __opt['segment'] = segment
        
        print 'Converting %s starting at %s \n' % (segment, datetime.now().isoformat(' '))
        cmd.task_queue.put(__opt)
            
        
    cmd.start() #start the compare worker threads
    cmd.task_queue.join() #wait for workers to finish
    cmd.flush() #flush the logs
    
    print "done."