import os
import json

import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.exceptions as exceptions
from azure.cosmos.partition_key import PartitionKey

from flask import Flask
app = Flask(__name__)

HOST = os.environ.get('COSMOSDB_URI', 'localhost')
MASTER_KEY = os.environ.get('SQLCONNSTR_RO_PRIMARY', 'XXX')
DATABASE_ID = os.environ.get('DATABASE_ID', 'SampleDB')
CONTAINER_ID = os.environ.get('CONTAINER_ID', 'Persons')

client = cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY} )
db = client.get_database_client(DATABASE_ID)
container = db.get_container_client(CONTAINER_ID)

def get_person_list(client):

    people = list(container.query_items(
        query="select p.firstname, p.age from Persons p",
        enable_cross_partition_query=True
    ))

    return json.dumps(people, indent=True, ensure_ascii=False)
    

def list_databases(client):
    print("\n4. List all Databases on an account")
    print('Databases:')

    databases = list(client.list_databases())

    if not databases:
        return

    for database in databases:
        return database['id']


@app.route("/")
def hello():
    return "Hello, World!"

@app.route("/list")
def get_list():
    try:
        return list_databases(client)
    except Exception as e:
        return "error"

@app.route("/people")
def get_people():
    try:
        return get_person_list(client)
    except Exception as e:
        return "error"

import os
import json

import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.exceptions as exceptions
from azure.cosmos.partition_key import PartitionKey

from flask import Flask
app = Flask(__name__)

HOST = os.environ.get('COSMOSDB_URI', 'localhost')
MASTER_KEY = os.environ.get('SQLCONNSTR_RO_PRIMARY', 'XXX')
DATABASE_ID = os.environ.get('DATABASE_ID', 'SampleDB')
CONTAINER_ID = os.environ.get('CONTAINER_ID', 'Persons')

client = cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY} )
db = client.get_database_client(DATABASE_ID)
container = db.get_container_client(CONTAINER_ID)

def get_person_list(client):

    people = list(container.query_items(
        query="select p.firstname, p.age from Persons p",
        enable_cross_partition_query=True
    ))

    return json.dumps(people, indent=True, ensure_ascii=False)
    

def list_databases(client):
    print("\n4. List all Databases on an account")
    print('Databases:')

    databases = list(client.list_databases())

    if not databases:
        return

    for database in databases:
        return database['id']


@app.route("/")
def hello():
    return "Hello, World!"

@app.route("/list")
def get_list():
    try:
        return list_databases(client)
    except Exception as e:
        return "error"

@app.route("/people")
def get_people():
    try:
        return get_person_list(client)
    except Exception as e:
        return "error"
