#!/usr/bin/python
########################################################################
#
# File Name:            GenerateStructure.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, OdlUtil, GenerateType

from Ft.Ods.MetaData import MetaKind
from Ft.Ods import Constants

from Ft.Ods.Exception import FtodsGenerationError

# File creation algorithms
def GenerateStubs(struct, params,fileName,useName,toSet):
    """File creation algorithms"""


    outFile = open(fileName,'a')

    outFile.write("\n# Begin Generation of Structure %s\n\n" % struct.name)

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

    d,names = BuildStructureData(params,struct)

    outFile.write("class %s(Structure.Structure):\n" % useName)

    outFile.write("    _definition = %s\n" % repr(d))
    
    outFile.write("    _typeId = %d\n" % struct._4ods_getId())
    outFile.write("    _typeIds = (%d,)\n" % struct._4ods_getId())
    outFile.write("    _tupleNames = %s\n" % repr(names))

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

    outFile.write("\n# End Generation of Structure %s\n\n" % struct.name)

    outFile.close()


    params.literalFiles.append((Constants.Types.STRUCTURE,fileName,[useName]))
    return



def BuildStructureData(params,struct):
    data = {}
    names = []

    for f in struct.fields:
        t = OdlUtil.NormalizeTypeDefinition(f.type)
        names.append(f.name)
        ot = t._4ods_getOdmgType()
        if Constants.g_primitiveTypes[ot]:
            default = eval(GenerateType.g_pyDefaultFromOdlType[t._4ods_getOdl('')])
        elif Constants.g_literalTypes[ot]:
            if t._4ods_getOdmgType() in [Constants.Types.STRUCTURE,
                                         Constants.Types.ENUMERATION]:
                rid = t._4ods_getId()
            else:
                rid = -1

            default = rid
        elif ot in [Constants.Types.POBJECT,Constants.Types.ROBJECT]:
            default = t._4ods_getId()
        elif Constants.g_listTypes[ot]:
            ct = t._4ods_getOdmgType()
            st = t.subtype._4ods_getOdmgType()
            strid = t.subtype._4ods_getId()
            if ot == Constants.Types.DICTIONARY_COLLECTION:
                kt = t.key_type._4ods_getOdmgType()
                ktrid = t.key_type._4ods_getId()
            else:
                kt = -1
                ktrid = -1
            default = (ct,st,strid,kt,ktrid)
        else:
            raise FtodsGenerationError(msg="Structure Members of type %s not supported" % t)

        data[f.name] = (t._4ods_getOdmgType(),default)

    return data, names






