import logging

from gzip import GzipFile
from flask import send_file, abort
from cStringIO import StringIO

from data.userfiles import DelegateUserfiles, UserfilesHandlers


JSON_MIMETYPE = 'application/json'


logger = logging.getLogger(__name__)


class LogArchiveHandlers(UserfilesHandlers):
  def get(self, file_id):
    path = self._files.get_file_id_path(file_id)
    try:
      with self._storage.stream_read_file(self._locations, path) as gzip_stream:
        with GzipFile(fileobj=gzip_stream) as unzipped:
          unzipped_buffer = StringIO(unzipped.read())
          return send_file(unzipped_buffer, mimetype=JSON_MIMETYPE)
    except IOError:
      abort(404)


class LogArchive(object):
  def __init__(self, app=None, distributed_storage=None):
    self.app = app
    if app is not None:
      self.state = self.init_app(app, distributed_storage)
    else:
      self.state = None

  def init_app(self, app, distributed_storage):
    location = app.config.get('LOG_ARCHIVE_LOCATION')
    path = app.config.get('LOG_ARCHIVE_PATH', None)

    handler_name = 'logarchive_handlers'

    log_archive = DelegateUserfiles(app, distributed_storage, location, path, handler_name)

    app.add_url_rule('/logarchive/<file_id>',
                     view_func=LogArchiveHandlers.as_view(handler_name,
                                                          distributed_storage=distributed_storage,
                                                          location=location,
                                                          files=log_archive))

    # register extension with app
    app.extensions = getattr(app, 'extensions', {})
    app.extensions['log_archive'] = log_archive
    return log_archive

  def __getattr__(self, name):
    return getattr(self.state, name, None)