

import os
DBNAME=os.environ.get("ODS_TEST_DB","ods:test")


from Ft.Ods.StorageManager.Adapters import Constants
from Ft.Ods.StorageManager import Adapters
from Ft.Ods import Collection

class DummyCollection(Collection.Collection):

    _collectionType = Constants.CollectionTypes.SET

    def __init__(self,db,cid,subType,subTypeRepoId,values):
        self.changes = []

        if values is not None:
            self._values = values
        else:
            self._values = {}
        

        Collection.Collection.__init__(self,db,cid)


    def _4ods_getSubType(self):
        return Constants.Types.STRING

    def _4ods_getSubRepositoryId(self):
        return Constants.Types.STRING

    def _4ods_getChanges(self):
        return self.changes

    def _4ods_isModified(self):
        return len(self.changes) > 0

    def _4ods_getOdsType(self):
        return Constants.Types.SET_COLLECTION

def Test(tester):

    tester.startGroup("Collection Driver %s" % tester.test_data['driver'])

    #Can't have a full DB here
    tester.startTest("Init DB")
    manager = Adapters.GetManager()
    adapter = Adapters.GetAdapter()
    if manager.exists(DBNAME):
        manager.reinit(DBNAME,adapter)
    else:
        manager.create(DBNAME)
        manager.init(DBNAME)

    tester.testDone()
    

    #Test the low level Collection Base
    from Ft.Ods import Database
    db = Database.Database()
    db.open(DBNAME)

    try:
        tester.startTest("Creation")
        tx = db.new()
        tx.begin()
        c = DummyCollection(db,None,None,-1,None)
        c.changes = [(Constants.CollectionChanges.APPEND,[("One",0),("Two",1)])]
        tx.commit()

        cid = c._4ods_getId()
        tester.testDone()

        tester.startTest("Getting it")
        tx = db.new()
        tx.begin()

        c = tx._4ods_getCollection(cid)

        tester.testResults(2,len(c._values),done=0,msg="Length")
        tester.testResults("One", c._values[0],done=0,msg="One")
        tester.testResults("Two", c._values[1],done=0,msg="Two")
        tx.abort()

    finally:
        tester.testDone()
        tester.groupDone()
        db.close()

