# use.py -- Select a line database

import os.path
import sys
import sicparse
import linedb
import pysic

def main():

   # Parse arguments and options

   parser = sicparse.OptionParser()
   parser.add_option( "-a", "--astro", dest="astro", action="store_true", default=False)
   parser.add_option( "-c", "--cache", dest="offline", action="store_true", default=False)
   parser.add_option( "-w", "--overwrite", dest="overwrite", action="store_true", default=False)

   try:
      (options, args) = parser.parse_args()
   except:
      pysic.message(pysic.seve.e, "USE", "Invalid option")
      pysic.sicerror()
      return
   if len(args) < 2:
      pysic.message(pysic.seve.e, "USE", "Incorrect number of arguments")
      pysic.sicerror()
      return
   validModes = ["in", "out", "both"]
   mode = validModes[sicparse.ambigs(args[0], validModes)]
   if len(args) != 2 and mode != "in":
      pysic.message(pysic.seve.e, "USE", "Multiple output databases not allowed")
      pysic.sicerror()
      return
   # setup input/output
   db_name = args[1:]

   # Clean the Sic structure(s)
   if mode in ["in","both"]:
     pysic.get('linedb',0)  # Get the global LINEDB% structure in the binding dictionary
     try:
       pysic.delete(pysic.gdict.linedb.dbin)
     except:
       pass
   if mode in ["out","both"]:
     pysic.get('linedb',0)  # Get the global LINEDB% structure in the binding dictionary
     try:
       pysic.delete(pysic.gdict.linedb.dbout)
     except:
       pass

   # Select the database
   try:
      linedb.use(db_name, mode,
                 online = not(options.offline),
                 overwrite=options.overwrite,
                 astro=options.astro)
#   except ValueError as error:
   except Exception as error:
      pysic.message(pysic.seve.e, "USE", "{0}".format(error))
      pysic.sicerror()
      return

   # Update the Sic structures
   if mode in ["in","both"]:
     leng = len(linedb.dbin.databases)
     charlen = max([len(x.name) for x in linedb.dbin.databases])
     pysic.define("CHARACTER LINEDB%%DBIN*%d[%d]" % (charlen,leng),True)
     for i in range(len(linedb.dbin.databases)):
       pysic.gdict.linedb.dbin[i] = linedb.dbin.databases[i].name
   if mode in ["out","both"]:
     leng = len(linedb.dbout.databases)
     charlen = max([len(x.name) for x in linedb.dbout.databases])
     pysic.define("CHARACTER LINEDB%%DBOUT*%d[%d]" % (charlen,leng),True)
     for i in range(len(linedb.dbout.databases)):
       pysic.gdict.linedb.dbout[i] = linedb.dbout.databases[i].name

   if mode == "out":
      return

   # Print informal message
   for d in linedb.dbin.databases:
      msg = d.name
      if d.online:
         msg += " (online) "
      else:
         msg += " (offline) "
      msg += "selected"
      if mode == "out":
         msg += " for output"
      if d.protocol == "catfile":
         dir = os.path.dirname(d.name)
         msg += " with {0}/(partfunc.json|partfunc.cat) for partition functions".format(dir)
      pysic.message(pysic.seve.i, "USE", "{0}".format(msg))

main()
