from odl import Database
from .models import (
    Table,          # Table model
    TableModel,     # Table data model
    Create,         # Create table request
    Insert,         # Insert data request
    Select,         # Select data request
    WhereFilter,    # Where filter
    Delete          # Delete data request
)

# Creating table data model
class User(TableModel):
    uid: int = 0
    username: str = ""
    phone: str = ""

# Creating table model
usertable = Table(
    name="users",
    model=User
)

# Creating or opening database (you can connect it to RAM with :memory: path)
db = Database("test.odb")

# Creating new user from pydantic model
user = User(
    uid=2318974,
    username="developer",
    phone="+9928773813913"
)

# Adding request to queue and waiting for response
#
# Why adding to queue and waiting instead of processing?
# Library have thread-based system for processing, its loop in background.
# Its more effective than processing in main thread and stop it while request is not done.
# Buuut in this example .process method stops main thread and waits for response.
# You can also use .addRequest method to add request to queue and not wait for response.
# In this case you need to use .isDone method to check if request is done or not.
# And .getResult method to get response.
r3 = db.process(
    Select(
        table=usertable,
        where=[
            WhereFilter(
                field="username",
                value="developer"
            )
        ]
    )
)
# Yes, result always returned. If it Select request, its list of objects, else - True/False.
print(f"Selected: {r3}")

r4 = db.process(
    Delete(
        table=usertable,
        where=[
            WhereFilter(
                field="username",
                value="developer"
            )
        ]
    )
)
# In this case you must got True response because Delete request cant return anything.
print(f"Deleted: {r4}")

# About internal methods
# .process method use .addRequest, .isDone and .getResult methods under the hood.
# .addRequest method add request to queue and not wait for response.
# .isDone method check if request is done or not.
# .getResult method get response, if request is not done - return None.

db._stop()