import sys

sys.path.append('TroubleShooter/Genexus/Tools/ft')
import matplotlib
if __name__ == '__main__':
    matplotlib.use( 'agg' )

import evaluate_qpm
import os

# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__

def getLatestPressureDirectory():
    softwareItems = os.listdir("/software")
    potentialFtFolders = []
    for item in softwareItems:
        if "ft_" in item:
            potentialFtFolders.append("/software/"+item)
    if potentialFtFolders == []:
        raise ValueError("Couldn't find most recent factory test results folder. Aborting.")
    ftFolderPath = max(potentialFtFolders, key=os.path.getctime)
    ftFolderItems = os.listdir(ftFolderPath)
    pressureDirectoryList = []
    for item in ftFolderItems:
        if "PipetteTransferTest" in item:
            pressureDirectoryList.append(ftFolderPath+'/'+item)
    if pressureDirectoryList == []:
        raise ValueError("Couldn't find most recent transfer test results folder. Aborting.")
    latestPressureDirectory = max(pressureDirectoryList,key=os.path.getctime)
    print("Analyzing transfer test: {}".format(latestPressureDirectory.split("/")[-1]))
    return latestPressureDirectory

def reanalyze(pressureDirectory):
    PASS_FAIL = 99.5
    pips_total_pass = [None,[0,0],[0,0]]
    num_bad_allowed = 1
    result = [PASS_FAIL,None,None]
    blockPrint()
    try:
        results = evaluate_qpm.run(inputdir=pressureDirectory)
    except:
        raise ValueError("QPM analysis unsuccessful: Please try again. If analysis continues to fail, please rerun the transfer test and then rerun analysis using this script.")
    enablePrint()
    for pip,idx in zip(['PIP1','PIP2'],[0,1]):
        if results[pip]:
            pass_num = results[pip]['PASS']['number']; pass_perc = results[pip]['PASS']['percent']
            warn_num = results[pip]['WARN']['number']; warn_perc = results[pip]['WARN']['percent']; warn_wells = results[pip]['WARN']['wells']
            fail_num = results[pip]['FAIL']['number']; fail_perc = results[pip]['FAIL']['percent']; fail_wells = results[pip]['FAIL']['wells']
            total_num = pass_num + warn_num + fail_num
            pips_total_pass[idx+1][0] = total_num
            pips_total_pass[idx+1][1] = pass_num
            result[idx+1]=round(pass_perc,3)
            print('')            
            print('   ***** RESULTS FOR {} *****'.format(pip))
            print('   ***** Total transfers: {}'.format(total_num))
            print('   ***** Normal Trace: {} ({} %)'.format(pass_num,round(pass_perc,3)))
            print('   ***** Required passing % of {} based on official guidance at time of TR release.'.format(PASS_FAIL))
            print('   ***** Please see your regional specialist for guidance on required passing percentage.')
            print('   ***** We allow for one bad transfer regardless of run configuration. For some configurations the pass % might be lower than {}.'.format(PASS_FAIL))
            if pass_perc <  PASS_FAIL and pass_num < total_num - num_bad_allowed:
                print('   ***** Pipette {} FAILED, The transfer pass rate of {}% is below the {}% threshold'.format(pip,round(pass_perc,3), PASS_FAIL))
            else:
                print("   ***** Pipette {} PASSED, The transfer pass rate of {}% is above the {}% threshold or only one transfer wasn't normal".format(pip,round(pass_perc,3), PASS_FAIL))
    pip_res = []
    i = 1
    while i < len(result):
        x = result[i]
        if x != 0.0:#if non zero evaluate.
            if x < PASS_FAIL:#if we fail, check "one bad trace" criteria
                if pips_total_pass[i][1] < pips_total_pass[i][0] -  num_bad_allowed:#passnum < total - 1
                    pip_res.append(x) #if more than 1 bad trace is found, append the real passrate is it should fail
                else:
                    pip_res.append(100) #if only 1 bad trace is found we pass with 100% (we already printed the real passrate above, this is just for pass/fail)
            else:
                pip_res.append(x)#if we pass, just add to the res array
        else:
            pip_res.append(x)
        i = i + 1
    if not all (x > PASS_FAIL for x in pip_res):
        replace_str = '   ***** Replace the tip adapter(s) on pipette(s) '
        i = 1
        while i < len(result):
            elem = result[i]
            if elem !=None and elem < PASS_FAIL:
                replace_str += str(i)+ ' & '
            i += 1
        replace_str = replace_str[:-1]
        print('')      
        print(' Transfer test failed')
        print('') 
        print(replace_str +'. If you have already replaced the tip adapter(s), replace the pipette(s)')
        print('   ***** Once the tip adapter(s) and/or pipette(s) have been replaced, please deckCal the instrument')
        print('   ***** After deckCal has successfully completed, please rerun this transfer test')
    else:
        print('') 
        print(' Transfer test passed')
        print('') 
             
if __name__ == '__main__':
    reanalyze(getLatestPressureDirectory())
