
import os ,shutil, subprocess
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_2(tmpdir):
    """ regression test for sample input called from CLI
    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/sampleInput.txt')
    reffile = resource_filename(Requirement.parse("ofrcalc"),'tests/refs/sampleOutputLong.csv')
    resDir = 'test-2-res/'
    picDir = 'test-2-pics/'

    getGradients = True
    absGradients = False
    
    ## call the CLI
    cmdstr = " ".join(['ofrcalc',str(infile),'--draw',
                        '--signed',
                        '--pic',picDir,'--res' ,resDir])
    print(cmdstr)
    p = subprocess.call(['ofrcalc',str(infile),'--draw',
                        '--signed',
                        '--pic',picDir,'--res' ,resDir]) 
    
    # 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 ['OA','SA']:
        for temp in ['45','120','150']:
            for speed in np.linspace(0.5, 10,5):
                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-2-res/')
    shutil.rmtree('test-2-pics/')
