#!/usr/bin/python
########################################################################
#
# File Name:            GenerateEnumuration.py
#
# Documentation:        http://docs.4suite.org/4ODS/ParsedEnumType.py.html
#

#Desc.
#WWW: http://4suite.org/4ODS        e-mail: support@4suite.org

#Copyright (c) 1999 Fourthought, Inc., USA.   All Rights Reserved.
#See  http://4suite.org/COPYRIGHT  for license and copyright information

import os
from Ft.Ods import Constants
# File creation algorithms
def GenerateStubs(enum, params,fileName,useName,toSet):
    """File creation algorithms"""

    outFile = open(fileName,'a')

    outFile.write("\n# Begin Generation of Enumeration %s\n\n" % enum.name)


    # The names may be in wanky order, let's sort'em
    eNames = enum.elements[:]
    eNames.sort(SortByValue)

    outFile.write("from Ft.Ods import Enumeration\n")



    outFile.write("class %sElement(Enumeration.EnumElement):\n" % enum.name)
    outFile.write("    nameMapping = {0:'%s',\n" % (eNames[0]))
    ctr =1
    for e in eNames[1:]:
        outFile.write("                   %d:'%s',\n" % (ctr,e))
        ctr = ctr + 1
                 
    outFile.write('    }\n');

    outFile.write('    def __init__(self,db,value):\n')
    outFile.write('        if value == None: value = 0\n')
    outFile.write('        if type(value) == type(()): value = value[0]\n')
    #outFile.write('        print value\n')
    outFile.write('        Enumeration.EnumElement.__init__(self,db,self.nameMapping[value],value,"%s",%d)\n\n\n'%(enum.name,enum._4ods_getId()))



    outFile.write("class %sEnum(Enumeration.Enumeration):\n" % (enum.name))
    ctr =0
    for e in eNames:
        outFile.write("    %s = %sElement(None,%d)\n" % (e,enum.name,ctr))
        ctr = ctr + 1
    outFile.write('\n\n')


    outFile.write("    def __init__(self):\n")
    outFile.write("        Enumeration.Enumeration.__init__(self,\n")
    outFile.write("                                         'MetaKind',\n")
    outFile.write("                                          %d,\n" % enum._4ods_getId())
    outFile.write("                                          [self.%s,\n"% eNames[0])
    for e in eNames[1:]:
        outFile.write("                                           self.%s,\n" % (e))
    outFile.write("                                           ])\n")


    outFile.write("%s = %sEnum()\n" % (useName,enum.name))

    if toSet:
        parentName, actualName = toSet
        outFile.write("%s.%s=%s\n" % (parentName,actualName,useName))

    outFile.write("\n# End Generation of Enumeration %s\n\n" % enum.name)

    outFile.close()

    for e in eNames:
        params.literalFiles.append((Constants.Types.ENUMERATION,fileName,[useName,str(e)]))
    return

def SortByValue(left,right):
    return cmp(left.value(),right.value())







