from os import getpid, stat
from os.path import isfile
from subprocess import Popen
from dakota_out_parse import *
from helpers import *


def postqmu(md):
    '''
    Deal with dakota output results in files.

    INPUT function
    md = postqmu(md)

    '''

    # check to see if dakota returned errors in the err file
    qmuerrfile = str(md.miscellaneous.name) + '.qmu.err'

    if isfile(qmuerrfile) and stat(qmuerrfile).st_size > 0:
        with open(qmuerrfile, 'r') as fide:
            fline = fide.read()
            print(fline)

        raise RuntimeError('Dakota returned error in ' + str(qmuerrfile) + ' file.')

    # parse inputs and results from dakota
    qmuinfile = str(md.miscellaneous.name) + '.qmu.in'
    qmuoutfile = str(md.miscellaneous.name) + '.qmu.out'
    [method, dresp_out, scm, pcm, srcm, prcm] = dakota_out_parse(qmuoutfile)
    dakotaresults = struct()
    dakotaresults.dresp_out = dresp_out
    dakotaresults.scm = scm
    dakotaresults.pcm = pcm
    dakotaresults.srcm = srcm
    dakotaresults.prcm = prcm

    if isfile('dakota_tabular.dat'):
        # only need a subset of the outputs; dakota_out_parse handles .dat seperately
        [method, dresp_dat, _, _, _, _] = dakota_out_parse('dakota_tabular.dat')
        dakotaresults.dresp_dat = dresp_dat

    # put dakotaresults in their right location.
    md.results.dakota = dakotaresults

    # move all the individual function evalutations into zip files
    if not md.qmu.isdakota:
        Popen('zip - mq params.in.zip params.in.[1 - 9] * ', shell=True)
        Popen('zip - mq results.out.zip results.out.[1 - 9] * ', shell=True)
        Popen('zip - mq matlab.out.zip matlab * .out.[1 - 9] * ', shell=True)

    return md
