import os
import sys

folder_path = 'C:/SWMM_log/' # setup runtime folder

# run test case and follow-up test case
for i in range(1):
    
	# setup runswmm.exe and swmm.dll
    swmm_path = folder_path + 'runswmm.exe'
    swmmdll_path = folder_path + 'swmm5.dll'
    os.rename(folder_path + 'runswmm_' + str(i) + '.exe', swmm_path)
    os.rename(folder_path + 'swmm5_' + str(i) + '.dll', swmmdll_path)

    # get input file
    inp_path = folder_path + 'test.inp'
    
	# get follow-up input file
    inp_path_2 = folder_path + 'follow_up_test.inp'
    
	# setup output file path
    rpt_path = folder_path + 'test' + str(i) + '.rpt'
    rpt_path_2 = folder_path + 'test' + str(i) + 'follow_up.rpt'

    # run tes case
    cmd = swmm_path + " " + inp_path + " " + rpt_path
    message = os.popen(cmd).read()
    if message.find("error") != -1:
        print("swmm error")
    else:
        print("swmm success")
    
	# run follow_up test case
    cmd2 = swmm_path + " " + inp_path_2 + " " + rpt_path_2
    message2 = os.popen(cmd2).read()
    if message2.find("error") != -1:
        print("swmm error")
    else:
        print("swmm success")
    
	# recover SWMM path
    os.rename(swmm_path, folder_path + 'runswmm_' + str(i) + '.exe')
    os.rename(swmmdll_path, folder_path + 'swmm5_' + str(i) + '.dll')

# check if the MR holds or not
for i in range(1):
    
    rpt_path = folder_path + 'test' + str(i) + '.rpt'
    rpt_path_2 = folder_path + 'test' + str(i) + 'follow_up.rpt'
	
	# read output files
    with open(rpt_path, 'r') as f1:
        contents1 = f1.readlines()
    with open(rpt_path_2, 'r') as f2:
        contents2 = f2.readlines()
    
	try:      
		# check outflow
        value1 = contents1[41].strip().replace('\n', '').replace('\r', '').split(' ')
        value2 = contents2[41].strip().replace('\n', '').replace('\r', '').split(' ')
        while '' in value1:
            value1.remove('')
        while '' in value2:
            value2.remove('')
        value1 = float(value1[-1].strip())
        value2 = float(value2[-1].strip())
        if value2 <= value1:
            print(i, 'MR holds')
		else:
			print(i, 'MR not holds')

        # # check continuity error
        # value1 = contents1[242].strip().replace('\n', '').replace('\r', '').split(' ')
        # value2 = contents2[242].strip().replace('\n', '').replace('\r', '').split(' ')
        # while '' in value1:
        #     value1.remove('')
        # while '' in value2:
        #     value2.remove('')
        # value1 = float(value1[-1].strip())
        # value2 = float(value2[-1].strip())
        # if value2 >= value1:
        #     print(i, 'MR holds')
		# else:
		#	  print(i, 'MR not holds')
    
	except:
        print('MR not holds')
