
import time, os
from jaguarlitepython import JaguarLite

''' Test simple data insert and select '''
def test_simple(db):

    db.execute("create table t1( key:  a int, value: b int )")
    
    db.startQuery("desc t1")
    db.read()
    msg = db.getMessage()
    print(f"{msg}")
    db.endQuery()
    
    print("\n")
    
    db.execute("insert into t1 values ('1', '100')")
    db.execute("insert into t1 values ('2', '200')")
    db.insert({ "table": "t1", "a": "3", "b": "300" })
    db.insert({ "table": "t1"}, ['4', '400'] )
    db.insert({ "table": "t1"}, ['5', '500'] )
    
    db.startQuery("select * from t1")
    while db.read():
        db.printRow()
        jsonmsg  = db.json()
        print(f"{jsonmsg}")
    if db.hasError():
        print(f"error={db.error()}")
    db.endQuery()


''' Test vector data insert and select '''
def test_vector(db):
    db.execute("create store vec1 ( v vector(10, 'cosine_fraction_float'), v:text char(64) )")
    
    db.execute("insert into vec1 values ( '0.8, 0.4, 0.2, 0.3, 0.7, 0.03, 0.3, 0.41, 0.2, 0.3', ' vector data of apple' ) ")
    db.execute("insert into vec1 values ( '0.7, 0.4, 0.1, 0.3, 0.5, 0.23, 0.6, 0.51, 0.1, 0.1', ' vector data of pear' ) ")
    db.execute("insert into vec1 values ( '0.2, 0.5, 0.3, 0.4, 0.6, 0.63, 0.4, 0.61, 0.3, 0.5', ' vector data of orange' ) ")
    
    
    db.startQuery("select similarity(v, '0.1, 0.2, 0.3, 0.4, 0.5, 0.3, 0.1, 0.5, 0.01, 0.2', 'topk=3,type=cosine_fraction_float') from vec1")

    while db.read():
        jsonmsg  = db.json()
        print(f"{jsonmsg}")
    if db.hasError():
        print(f"error={db.error()}")
    db.endQuery()


''' Test data encryption and decryption '''
def test_encrypt(db):
    keyfile = "/tmp/mypyenc.key"
    key = ""
    if os.path.exists( keyfile ):
        ### Do not recreate again. If so, existing data in database cannot be decrypted
        ### because the key is different now.
        key = db.readEncryptionKey(keyfile)
    else:
        key = db.createEncryptionKey( keyfile ) 
        
    db.execute("create store vault ( name char(128), id char(128) )")

    ### Two ways to insert encrypted data: 1: API, 2: use the key string
    ## API
    encryptedName = db.encryptWithGivenKey('jamesbond', key)
    encryptedID = db.encryptWithGivenKey('007', key)
    db.execute(f"insert into vault values ('{encryptedName}', '{encryptedID}')")
    zid1 = db.getLastZuid()

    ## embedded string
    db.execute(f"insert into vault values ( encrypt('janedoe', '{key}'), encrypt('018', '{key}') )")
    zid2 = db.getLastZuid()

    ### select, showing encrypted data 
    db.startQuery("select * from vault")
    while db.read():
        jsonmsg  = db.json()
        print(f"{jsonmsg}")
    db.endQuery()

    ### select and decrypt
    db.startQuery(f"select decrypt(name,'{key}'), decrypt(id,'{key}') from vault")
    while db.read():
        jsonmsg  = db.json()
        print(f"{jsonmsg}")
    db.endQuery()

    ### select one 
    db.startQuery(f"select decrypt(name,'{key}'), decrypt(id,'{key}') from vault where zid='{zid1}'")
    db.read()
    jsonmsg  = db.json()
    print(f"{jsonmsg}")
    db.endQuery()


if __name__ == '__main__':

    #### create or use mydb of customer1
    db1 = JaguarLite("mydb", "customer1")
    test_simple(db1)


    #### create or use vectordb of customer2
    db2 = JaguarLite("myvectordb", "customer2") 
    test_vector(db2)


    ### test encrypt/decrypt
    securedb = JaguarLite("mydb", "secretcustomer");
    test_encrypt( securedb )


