
import os ,shutil
import numpy as np

from pkg_resources import resource_filename, Requirement
from ofrcalc.routines.iomanager import loadInputFile, resultRead
from ofrcalc.routines.runmanager import multiRunManager
from ofrcalc.routines.inputparser import createParser

def test_3(tmpdir):
    """ regression test for sample input II called as a python API.
    using signed gradient drawing
    """
    
    # squelch some TF output
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    os.environ['KMP_WARNINGS'] = '0'
    
    # set paramteters
    infile = resource_filename(Requirement.parse("ofrcalc"),'ofrcalc/examples/sampleInputTwo.txt')
    reffile = resource_filename(Requirement.parse("ofrcalc"),'tests/refs/sampleOutputTwo.csv')
    vrange = np.linspace(0.25,10.25,50)
    resDir = 'test-3-res/'
    picDir = 'test-3-pics/'

    getGradients = True
    absGradients = False
    
       
    # get the inputs
    ins  = loadInputFile(str(infile))
    
                
    # pass the inputs to the caller:
    r = multiRunManager(inputList = ins,\
                        vrange = vrange,\
                        picDir = picDir, \
                        resDir = resDir, \
                        getGradients = getGradients,\
                        absGradients = absGradients)
    
    # assert job completed normally
    assert r == 0
    
    # test if the file was created
    assert os.path.isfile(resDir+'results.csv')
    
    # test if the expected values were obtained by comparison to the reference
    realN, realMean = resultRead(resDir+'results.csv')
    targetN, targetMean = resultRead(reffile)
    assert int(realN)-int(targetN) == 0
    assert abs(float(realMean)-float(targetMean)) <= 1e-5
    
    # test if the pics were created 
    for OFR in ['GMO']:
        for temp in ['45','120','150']:
            for speed in vrange:
                for cov in ['low','medium']:
                    OFRPicName = "_".join([OFR,'speed',str(speed),'temp',temp,'cov',cov])+'.png'
                    path = "/".join([picDir,OFR,OFRPicName])
                    assert os.path.isfile(path)
    
    shutil.rmtree('test-3-res/')
    shutil.rmtree('test-3-pics/')
