import types
from Ft.Ods import Constants

class FixedString:
    "FixedString\n\tfs=FixedString('hello',2) is 'he'; fs.value='hippo' is 'hi'"
    def __init__(self,db,st): #data="",max_size=None):

        self.__dict__['db'] = db


        if type(st) == type(()):
            st = st[0]

        self.__dict__['value'] = st or ""
        Constants.StringTypeCheck(self.value,-1)
        if len(self.value) > self.max_size:
            raise ValueError("Fixed Length String can only be %d in length" % self.max_size)


    def __setattr__(self,attr,newvalue):
        if attr=="max_size":
            raise AttributeError("You Scannot set a FixedString max_size attribute")
        if attr=="value":
            Constants.StringTypeCheck(newvalue,-1)
            if len(newvalue) > self.max_size:
                raise ValueError("Fixed Length String can only be %d in length" % self.max_size)
            newvalue = str(newvalue)[0:self.max_size]
        self.__dict__[attr] = newvalue
        return 1

##    def __getattr__(self,name):
##        """Provided to make it look like a Python 2.* string"""
##        return getattr(self.__dict__['value'],name)

    # Later it occured to me that __coerce__ might be an easy way
    # to get rid of many of the math/string ops in one fell swoop.
    # NO     didn't work out well
    #def __coerce__(self,othertype):
    #    print "coerce called"
    #    return (str(self.value),str(othertype))
    #    pass
    def __len__(self):
        return len(self.value)
    def __getitem__(self,key):
        return self.value[key]
    def __add__(self,t):
        return self.value + t
    def __radd__(self,t):
        return t + self.value
    def __mul__(self,t):
        return self.value * t
    def __rmul__(self,t):
        return self.value * t
    def __mod__(self,t):
        return self.value % t
    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return repr(self.value)
    # These ones are for more esoteric functions:
    def __getslice__(self,i,j):
        return self.value[i:j]
    def __cmp__(self,other):
        return cmp(self.value,str(other))
    def __hash__(self):
        return hash(self.value)
    def __nonzero__(self):
        if self.value: return 1
        return 0
    # These ones supply Ods functions for a 'systemType'
    def _4ods_getData(self):
        return (self.value,)
    def _4ods_isModified(self):
        return 1 # ??? XXX

