import CoolProp
import os

web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..'))
root_dir = os.path.abspath(os.path.join(web_dir, '..')) 

fluid_template = """.. _fluid_{fluid:s}:

{fluid_stars:s}
{fluid:s}
{fluid_stars:s}

{references:s}
{aliases:s}

Fluid Information
=================

.. csv-table::
   :header-rows: 1
   :widths: 40, 60
   :file: {fluid:s}-info.csv
   
REFPROP Validation Data
=======================

.. note::

    This figure compares the results generated from CoolProp and those generated from REFPROP.  They are all results obtained in the form :math:`Y(T,\\rho)`, where :math:`Y` is the parameter of interest and which for all EOS is a direct evaluation of the EOS
    
    You can download the script that generated the following figure here: :download:`(link to script)<REFPROPplots/{fluid:s}.py>`, right-click the link and then save as... or the equivalent in your browser.  You can also download this figure :download:`as a PDF<REFPROPplots/{fluid:s}.pdf>`. 

.. image:: REFPROPplots/{fluid:s}.png

Consistency Plots
=================

The following figure shows all the flash routines that are available for this fluid.  A red + is a failure of the flash routine, a black dot is a success.  Hopefully you will only see black dots.  The red curve is the maximum temperature curve, and the blue curve is the melting line if one is available for the fluid.

In this figure, we start off with a state point given by T,P and then we calculate each of the other possible output pairs in turn, and then try to re-calculate T,P from the new input pair.  If we don't arrive back at the original T,P values, there is a problem in the flash routine in CoolProp.  For more information on how these figures were generated, see :py:mod:`CoolProp.Plots.ConsistencyPlots`

.. note::

    You can download the script that generated the following figure here: :download:`(link to script)<Consistencyplots/{fluid:s}.py>`, right-click the link and then save as... or the equivalent in your browser.  You can also download this figure :download:`as a PDF<Consistencyplots/{fluid:s}.pdf>`. 

.. image:: Consistencyplots/{fluid:s}.png

"""

table_template = """ Parameter, Value
**General**,
Molar mass [kg/mol],{mm:s}
CAS number, {CAS:s}
ASHRAE class, {ASHRAE:s}
**Limits**,
Maximum temperature [K],{Tmax:s}
Maximum pressure [Pa],{pmax:s}
**Triple point**,
Triple point temperature [K],{Tt:s}
Triple point pressure [Pa], {pt:s}
**Critical point**,
Critical point temperature [K], {Tc:s}
Critical point density [kg/m3], {rhoc_mass:s}
Critical point density [mol/m3], {rhoc_molar:s}
{reducing_string:s}
"""

reducing_template = """**Reducing point**,
Reducing point temperature [K], {Tr:s}
Reducing point density [mol/m3], {rhor_molar:s}
"""

bibtex_keys = ['EOS','CP0','CONDUCTIVITY','VISCOSITY','MELTING_LINE']
bibtex_map = {'EOS': 'Equation of State',
              'CP0': 'Ideal gas specific heat',
              'CONDUCTIVITY': 'Thermal Conductivity',
              'VISCOSITY': 'Viscosity',
              'MELTING_LINE': 'Melting Line'}

from pybtex.database.input import bibtex
parser = bibtex.Parser()
bibdata = parser.parse_file(os.path.join(root_dir,"CoolPropBibTeXLibrary.bib"))

# See http://stackoverflow.com/questions/19751402/does-pybtex-support-accent-special-characters-in-bib-file/19754245#19754245
import pybtex
style = pybtex.plugin.find_plugin('pybtex.style.formatting', 'plain')()
backend = pybtex.plugin.find_plugin('pybtex.backends', 'html')()
parser = pybtex.database.input.bibtex.Parser()    

def entry2html(entry):
    for e in entry:
        return e.text.render(backend).replace('{','').replace('}','').replace('\n', ' ')

def generate_bibtex_string(fluid):
    string = ''
    for key in bibtex_keys:
        try:
            # get the item
            bibtex_key = CoolProp.CoolProp.get_BibTeXKey(fluid,key).strip()
            if bibtex_key.strip() in bibdata.entries.keys():
                entry = style.format_entries([bibdata.entries[bibtex_key.strip()]])
                html = entry2html(entry)
                sect = bibtex_map[key]
                string += sect+'\n'+'-'*len(sect)+'\n\n.. raw:: html\n\n   '+html+'\n\n'
        except ValueError as E:
            pass
    return string

class FluidInfoTableGenerator(object):
    
    def __init__(self, name):
    
        self.name = name
        
    def write(self, path):
        def tos(n):
            ''' convert number to nicely formatted string '''
            n = str(n)
            if 'e' in n:
                n = n.replace('e',':math:`\times 10^{')
                n += '}`'
            else:
                return n
        molar_mass = CoolProp.CoolProp.PropsSI(self.name,'molemass')
        Tt = CoolProp.CoolProp.PropsSI(self.name,'Ttriple')
        Tc = CoolProp.CoolProp.PropsSI(self.name,'Tcrit')
        Tr = CoolProp.CoolProp.PropsSI(self.name,'T_reducing')
        pc = CoolProp.CoolProp.PropsSI(self.name,'pcrit')
        pt = CoolProp.CoolProp.PropsSI(self.name,'ptriple')
        Tmax = CoolProp.CoolProp.PropsSI(self.name,'Tmax')
        pmax = CoolProp.CoolProp.PropsSI(self.name,'pmax')
        rhoc_mass = CoolProp.CoolProp.PropsSI(self.name,'rhomass_critical')
        rhoc_molar = CoolProp.CoolProp.PropsSI(self.name,'rhomolar_critical')
        rhor_molar = CoolProp.CoolProp.PropsSI(self.name,'rhomolar_reducing')
        
        CAS = CoolProp.CoolProp.get_fluid_param_string(self.name, "CAS")
        ASHRAE = CoolProp.CoolProp.get_fluid_param_string(self.name, "ASHRAE34")
        
        # Generate (or not) the reducing data
        reducing_data = ''
        if abs(Tr - Tc) > 1e-3:
            reducing_data = reducing_template.format(Tr = tos(Tr), 
                                                     rhor_molar = tos(rhor_molar))
            
        args = dict(mm = tos(molar_mass),
                    Tt = tos(Tt),
                    pt = tos(pt),
                    Tc = tos(Tc),
                    rhoc_mass = tos(rhoc_mass),
                    rhoc_molar = tos(rhoc_molar),
                    pc = tos(pc),
                    CAS = tos(CAS),
                    ASHRAE = tos(ASHRAE),
                    Tmax = tos(Tmax),
                    pmax = tos(pmax),
                    reducing_string = reducing_data)
        out = table_template.format(**args)
        
        with open(os.path.join(path, self.name+'-info.csv'),'w') as fp:
            print 'writing', os.path.join(path, self.name+'-info.csv')
            fp.write(out)
            
class FluidGenerator(object):
    def __init__(self, fluid):
        self.fluid = fluid
        
    def write(self, path):
        
        # Write CSV table data for fluid information
        ITG = FluidInfoTableGenerator(self.fluid)
        ITG.write(path)
        
        aliases = ', '.join(['``' + a.strip() + '``' for a in CoolProp.CoolProp.get_fluid_param_string(self.fluid, 'aliases').strip().split(',') if a])
        if aliases:
            aliases = 'Aliases\n=======\n\n'+aliases + '\n'
        
        references = generate_bibtex_string(self.fluid)
        if references:
            references = 'References\n==========\n'+references+'\n'

        # Write RST file for fluid
        out = fluid_template.format(aliases = aliases,
                                    fluid = self.fluid,
                                    fluid_stars = '*'*len(self.fluid),
                                    references = references
                                    )
        
        with open(os.path.join(path, self.fluid+'.rst'),'w') as fp:
            print 'writing', os.path.join(path, self.fluid+'.rst')
            fp.write(out)