
from hawkSoar.storage.db_interface import DBInterface


class ViewSyncDb(DBInterface):
    '''
    View Syncing
    '''

    def __init__(self, config=None):
        super().__init__(config=config)
        # set table that needs to be updated.
        #self.view_storage = self.client
        #self.view_collection = self.client[self.config['data_storage']['view_storage']]
        #self.view_storage = gridfs.GridFS(self.view_collection)


class ViewUpdater(ViewSyncDb):
    """ Updates the HTML view for a given plugin."""

    READ_ONLY = False

    def update_view(self, plugin_name, content):
        query = 'UPDATE plugin_view set html={} WHERE plugin_name={}'.format(
            content, plugin_name)
        with self.client.connect() as conn:
            try:
                conn.execute(query)
            except Exception as e:
                # TODO: Handle errors
                pass


class ViewReader(ViewSyncDb):

    READ_ONLY = True

    def get_view(self, plugin_name):
        query = 'SELECT html FROM plugin_view WHERE plugin_name={}'.format(
            plugin_name)
        with self.client.connect() as conn:
            try:
                view = conn.execute(query)
            except Exception as e:
                # TODO: Handle errors
                pass
        if view:
            return view.read()
        else:
            return None
