import os,shutil

"""
A little script to wrap the params enum for use in Cython code

Ian Bell, May 2014
"""

def params_constants(enum_key):
    fName = os.path.join('..','..','include','DataStructures.h')
    
    contents = open(fName,'r').read()
        
    left = contents.find('{', contents.find('enum '+enum_key));
    right = contents.find('}', left)
    entries = contents[left+1:right]

    if entries.find('/*') > -1: raise ValueError('/* */ style comments are not allowed, replace them with // style comments')
    if not entries: raise ValueError('Unable to find '+enum_key)
        
    lines = entries.split('\n')
    lines = filter(lambda line: not line.strip().startswith('//') and line, lines)
    
    for i,line in enumerate(lines):
        if line.find('/'):
            lines[i] = line.split('/')[0]
    
    # Chomp all the whitespace, split at commas
    keys = ''.join(lines).replace(' ','').split(',')
    
    keys = filter(lambda k: k, keys)
        
    return keys

def generate_cython(data):

    #Write the PXD definition file
    pxd_output_file = open('constants_header.pxd','w')
    pxd_output_file.write('# This file is automatically generated by the generate_constants_module.py script in dev/scripts.\n# DO NOT MODIFY THE CONTENTS OF THIS FILE!\n\ncdef extern from "DataStructures.h" namespace "CoolProp":\n')
    
    for enum_key, entries in data:
        pxd_output_file.write('\tenum '+enum_key+':\n')
        for param in entries:
            param = param.strip()
            pxd_output_file.write('\t\t'+param+'\n')
    pxd_output_file.close()
    
    #Write the PYX implementation file
    pyx_output_file = open('constants.pyx','w')
    pyx_output_file.write('# This file is automatically generated by the generate_constants_module.py script in dev/scripts.\n# DO NOT MODIFY THE CONTENTS OF THIS FILE!\ncimport constants_header\n\n')
    for enum_key, entries in data:
        for param in entries:
            param = param.strip()
            pyx_output_file.write(param+' = '+'constants_header.'+param+'\n')
    pyx_output_file.close()
    
    shutil.copy2('constants_header.pxd',os.path.join('..','..','wrappers','Python','CoolProp5','constants_header.pxd'))
    shutil.copy2('constants.pyx',os.path.join('..','..','wrappers','Python','CoolProp5','constants.pyx'))
        
if __name__=='__main__':
    data = [(enum,params_constants(enum)) for enum in ['parameters', 'input_pairs', 'fluid_types']]
    generate_cython(data)