import sys
import glob
import threading
from subprocess import Popen, PIPE

from config.settings import *
from settings import *

from util.log import log

def run_pg_fouine():

    e = { }
    for k, v in os.environ.iteritems(): e[k] = v
    
    filelist = glob.glob(LOGS_PATH + '/*.csv.gz')

    if filelist:
        cat_options = [ 'gunzip', '-c' ] + sorted(filelist)
    else:
        filelist = glob.glob(LOGS_PATH + '/*.csv')
        if not filelist:
            log('No log files found')
            return
        
        cat_options = [ 'cat' ]  + sorted(filelist)

    pgfouine_stdout = open(PGFOUINE_REPORT_PATH, 'w')
    pgfouine_stderr = open(PGFOUINE_ERROR_PATH, 'w')
    
    pgfouine_options = [ PGFOUINE_PATH,
        '-logtype',
        'csvlog',
        '-' ]
        
    log('Starting pgfouine.')
    
    cat = Popen(cat_options, 
        stdout=PIPE, stderr=sys.stderr,
        env = e
        )
    pgfouine = Popen(pgfouine_options, 
        stdin=cat.stdout, stdout=pgfouine_stdout, stderr=pgfouine_stderr,
        env = e
        )
    
    cat.stdout.close()   # Magic!
    
    pgfouine.communicate()
    
    pgfouine_stdout.close()
    pgfouine_stderr.close()

    log('pgfouine done.')
    


def start_pg_fouine():

    class FouineWorker(threading.Thread):
        
        def run(self):
            run_pg_fouine()
    
    th = FouineWorker()
    th.start()
    
    return th