# This will be the common prelude to all of our TinyDB queries. 
import sys     # talk to the operating system 
import os.path # manipulate paths to files, directories 
import pprint  # pretty print JSON

import tinydb
from tinydb import Query


db_loc = sys.argv[1] # first command-line argument -- the directory containing the json database snapshot.


tdb = tinydb.TinyDB(os.path.join(db_loc, 'movies.tinydb.json'))
tdb_movies = tdb.table("movies")
tdb_people = tdb.table("people")


# Use this output routine to display table style output. You can adapt it
# to write directly to the output file for exercise submission.
def display_ans(ans, line_limit=250):
    ans = sorted(ans)        # Sort into ascending order
    ans = ans[0:line_limit]  # Limit number of entries
    cos = None
    if (True):
        cos = open(f'TINY1.txt', mode='w')    
        cos.write("-ANSWER-START-\n")


    for item in ans:
        print(f'{item}')
        if (cos != None): cos.write(f'{item}\n')
    print(f'Returned {len(ans)} records')

    if (cos != None):
        cos.write("-ANSWER-END-\n")
        cos.close()    


# An example of ad-hoc (user-level) scanning (easier to instrument if requested):
def get_person_by_name(str): 
    # initialise output 
    the_person = None
    # iterate through all the keys of the database looking for one with the right name
    for person_id in tdb_people:
        if ("name" in person_id):
            #print(f'{person_id["name"]}')
            if person_id['name'] == str:
                the_person = person_id
                break
    return the_person

# An example of TinyDB lookup:
def get_person_by_name(str): 
    m = Query()
    the_person = tdb_people.get(m.name == str)
    return the_person


#####################################
# write your query code here ... 

my_actors = ...

def demo1_question():
    ans = []
    for actor in my_actors:
        count = tdb_movies.count(Query().actors.any(Query().name == actor))
        line = f'{actor}, {count}'
        ans.append(line)
    display_ans(ans)


# eof
