# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""
    invenio.modules.records.api
    ---------------------------

"""

from invenio.modules.jsonalchemy.jsonext.engines.sqlalchemy import SQLAlchemyStorage
from invenio.modules.jsonalchemy.parser import FieldParser
from invenio.modules.jsonalchemy.registry import readers
from invenio.modules.jsonalchemy.wrappers import SmartJson

from .models import RecordMetadata as RecordMetadataModel
from .models import Record as RecordModel


class Record(SmartJson):
    """
    Default/Base record class
    """

    storage_engine = SQLAlchemyStorage(RecordMetadataModel)

    @classmethod
    def create(cls, blob, master_format, **kwargs):
        reader = readers[master_format](blob, namespace='recordext', **kwargs)
        return cls(reader.translate())

    @classmethod
    def get_record(cls, recid):
        try:
            json = cls.storage_engine.get_one(recid)
            return Record(json)
        except:
            # try to retrieve the record from the master format if any
            # this might be deprecated in the near future as soon as json will
            # become the master format, until then ...
            blob = cls.get_blob(recid)
            record_model = RecordModel.query.get(recid)
            if record_model is None or blob is None:
                return None
            additional_info = record_model.additional_info \
                    if record_model.additional_info else {'master_format': 'marc'}
            record = cls.create(blob, record_model.master_format, **additional_info)
            record._save()
            record_model.additional_info = \
                    record.get('__meta_metadata__.__additional_info__', {'master_format': 'marc'})
            record_model.commit()
            return record

    @staticmethod
    def get_blob(recid):
        #FIXME: start using bibarchive or bibingest for this
        from invenio.modules.formatter.models import Bibfmt
        from zlib import decompress

        record_blob = Bibfmt.query.get((recid, 'xm'))
        if record_blob is None:
            return None
        return decompress(record_blob.value)

    def _save(self):
        self.storage_engine.save_one(self.dumps())

# Functional interface
create_record = Record.create
get_record = Record.get_record













@@ -857,16 +857,62 @@
 -%0A%0A%22%22%22%0A%0A
+from sqlalchemy.orm.exc import NoResultFound%0A%0A
 from inv
@@ -1748,16 +1748,30 @@
   except
+ NoResultFound
 :%0A      

fix apache configuration