import sys
import logging

import matplotlib.pyplot as plt
import numpy as np
import faulthandler
faulthandler.enable()
plt.ion()

handler = logging.StreamHandler(sys.stderr)
fmt = logging.Formatter("%(asctime)-15s [%(name)5s:%(levelname)s] %(message)s")
handler.setFormatter(fmt)
handler.setLevel(logging.INFO)

logging.getLogger('hxntools').addHandler(handler)
logging.getLogger('hxnfly').addHandler(handler)
logging.getLogger('ppmac').addHandler(handler)

logging.getLogger('hxnfly').setLevel(logging.DEBUG)
logging.getLogger('hxntools').setLevel(logging.DEBUG)
logging.getLogger('ppmac').setLevel(logging.INFO)

import pandas as pd

# Flyscan results are shown using pandas. Maximum rows/columns to use when
# printing the table:
pd.options.display.width = 180
pd.options.display.max_rows = None
pd.options.display.max_columns = 10


from metadatastore.mds import MDS
from databroker import Broker
from databroker.core import register_builtin_handlers
from filestore.fs import FileStore

_mds_config = {'host': 'xf03id-ca1',
               'port': 27017,
               'database': 'datastore-new',
               'timezone': 'US/Eastern'}
mds = MDS(_mds_config, auth=False)

_fs_config = {'host': 'xf03id-ca1',
              'port': 27017,
              'database': 'filestore-new'}
db_new = Broker(mds, FileStore(_fs_config))

_mds_config_old = {'host': 'xf03id-ca1',
               'port': 27017,
               'database': 'datastore',
               'timezone': 'US/Eastern'}
mds_old = MDS(_mds_config_old, auth=False)

_fs_config_old = {'host': 'xf03id-ca1',
              'port': 27017,
              'database': 'filestore'}
db_old = Broker(mds_old, FileStore(_fs_config_old))


from hxntools.handlers.xspress3 import Xspress3HDF5Handler
from hxntools.handlers.timepix import TimepixHDF5Handler

register_builtin_handlers(db_new.fs)

db_new.fs.register_handler(Xspress3HDF5Handler.HANDLER_NAME,
                           Xspress3HDF5Handler)
db_new.fs.register_handler(TimepixHDF5Handler._handler_name,
                           TimepixHDF5Handler, overwrite=True)


register_builtin_handlers(db_old.fs)
db_old.fs.register_handler(Xspress3HDF5Handler.HANDLER_NAME,
                           Xspress3HDF5Handler)
db_old.fs.register_handler(TimepixHDF5Handler._handler_name,
                           TimepixHDF5Handler, overwrite=True)


# wrapper for two databases
class Broker_New(Broker):

    def __getitem__(self, key):
        try:
            return db_new[key]
        except ValueError:
            return db_old[key]

    def get_table(self, *args, **kwargs):
        try:
            return db_new.get_table(*args, **kwargs)
        except:
            return db_old.get_table(*args, **kwargs)

    def get_images(self, *args, **kwargs):
        try:
            return db_new.get_images(*args, **kwargs)
        except:
            return db_old.get_images(*args, **kwargs)


db = Broker_New(mds, FileStore(_fs_config))


def remove_names_maybe(obj, names):
    for n in names:
        try:
            obj.read_attrs.remove(n)
        except ValueError:
            pass
    return obj

@@ -2586,39 +2586,24 @@
         
-try:%0A            return
+result =
  db_new.
@@ -2629,38 +2629,51 @@
 kwargs)%0A        
-except
+if len(result) == 0
 :%0A            re
@@ -2664,36 +2664,38 @@
 :%0A            re
-turn
+sult =
  db_old.get_tabl
@@ -2712,16 +2712,38 @@
 *kwargs)
+%0A        return result
 %0A%0A    de
@@ -2787,39 +2787,24 @@
         
-try:%0A            return
+result =
  db_new.
@@ -2839,22 +2839,35 @@
         
-except
+if len(result) == 0
 :%0A      
@@ -2870,28 +2870,30 @@
           re
-turn
+sult =
  db_old.get_
@@ -2916,16 +2916,38 @@
 kwargs)%0A
+        return result%0A
 %0A%0Adb = B

check if results is None or not