#!/usr/bin/env python3

import json
import MemoizeDB
import sqlite3
import sys
import urllib.parse
import urllib.request


# The retriever function.
def get_pkginfo(names):
  for name in names:
    encoded_name = urllib.parse.quote(name)
    url = 'https://aur.archlinux.org/rpc.php?type=info&arg={}'.format(encoded_name)
    with urllib.request.urlopen(url) as f:
      yield name, (f.read().decode(),)

# The glue for handling the database. 300: cache the data for 5 minutes.
glue = {
  'pkginfo' : (get_pkginfo, (('json', 'TEXT'),), 300)
}

# The connection.
conn = sqlite3.connect(
  'test.sqlite3',
  detect_types=(sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES),
  isolation_level=None
)
mdb = MemoizeDB.MemoizeDB(conn, glue)
mdb.db_initialize()

# A wrapper function to convert the JSON text to an object.
def get_obj(name):
  txt = mdb.get_one('pkginfo', name)
  return json.loads(txt)

if sys.argv[1:]:
  names = sys.argv[1:]
else:
  names = ('python3-memoizedb', 'python3-aur', 'powerpill', 'bauerbill')

# Display the data.
for name in names:
  obj = get_obj(name)
  print(json.dumps(obj, indent=2, sort_keys=True))