# Path: yithlibraryserver/compat.py
# PY3 = sys.version_info[0] == 3
#     def encode_header(obj):  # pragma: no cover
#     def encode_header(obj):  # pragma: no cover
# 
# Path: yithlibraryserver/password/models.py
# class PasswordsManager(object):
# 
#     def __init__(self, db):
#         self.db = db
# 
#     def create(self, user, password):
#         """Creates and returns a new password or a set of passwords.
# 
#         Stores the password in the database for this specific user
#         and returns a new dict with the 'owner' and '_id' fields
#         filled.
# 
#         If password is a list, do the same with each password in
#         this list.
#         """
#         if isinstance(password, dict):
#             if password:
#                 new_password = dict(password)  # copy since we are changing this object
#                 new_password['owner'] = user['_id']
#                 _id = self.db.passwords.insert(new_password, safe=True)
#                 new_password['_id'] = _id
#                 return new_password
#         else:
#             new_passwords = []  # copy since we are changing this object
#             for p in password:
#                 if p:
#                     p = dict(p)
#                     p['owner'] = user['_id']
#                     new_passwords.append(p)
# 
#             if new_passwords:
# 
#                 _ids = self.db.passwords.insert(new_passwords, safe=True)
# 
#                 for i in range(len(new_passwords)):
#                     new_passwords[i]['_id'] = _ids[i]
# 
#                 return new_passwords
# 
#     def retrieve(self, user, _id=None):
#         """Return the user's passwords or just one.
# 
#         If _id is None return the whole set of passwords for this
#         user. Otherwise, it returns the password with that _id.
#         """
#         if _id is None:
#             return self.db.passwords.find({'owner': user['_id']})
#         else:
#             return self.db.passwords.find_one({
#                     '_id': _id,
#                     'owner': user['_id'],
#                     })
# 
#     def update(self, user, _id, password):
#         """Update a password in the database.
# 
#         Return the updated password on success or None if the original
#         password does not exist.
#         """
#         new_password = dict(password)  # copy since we are changing this object
#         new_password['owner'] = user['_id']
#         result = self.db.passwords.update({
#                 '_id': _id,
#                 'owner': user['_id'],
#                 }, new_password, safe=True)
#         new_password['_id'] = _id
# 
#         # result['n'] is the number of documents updated
#         # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue
#         if result['n'] == 1:
#             return new_password
#         else:
#             return None
# 
#     def delete(self, user, _id=None):
#         """Deletes a password from the database or the whole set for this user.
# 
#         Returns True if the delete is succesfull or False otherwise.
#         """
#         query = {'owner': user['_id']}
#         if _id is not None:
#             query['_id'] = _id
# 
#         result = self.db.passwords.remove(query, safe=True)
#         return result['n'] > 0
# 
# Path: yithlibraryserver/utils.py
# def remove_attrs(dictionary, *attrs):
#     """Returns a copy of dictionary without attrs"""
#     result = {}
# 
#     for key, value in dictionary.items():
#         if key not in attrs:
#             result[key] = value
# 
#     return result


import gzip
import json
from yithlibraryserver.compat import BytesIO
from yithlibraryserver.password.models import PasswordsManager
from yithlibraryserver.utils import remove_attrs
# 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 Affero General Public License
# along with Yith Library Server.  If not, see <http://www.gnu.org/licenses/>.




def get_user_passwords(db, user):
    passwords_manager = PasswordsManager(db)
    return [remove_attrs(password, 'owner', '_id')
            for password in passwords_manager.retrieve(user)]


def get_backup_filename(date):
    return 'yith-library-backup-%d-%02d-%02d.yith' % (
        date.year, date.month, date.day)


def compress(passwords):
    buf = BytesIO()
    gzip_data = gzip.GzipFile(fileobj=buf, mode='wb')
    data = json.dumps(passwords)
    gzip_data.write(data.encode('utf-8'))
    gzip_data.close()
    return buf.getvalue()


def uncompress(compressed_data):

# Path: yithlibraryserver/compat.py
# PY3 = sys.version_info[0] == 3
#     def encode_header(obj):  # pragma: no cover
#     def encode_header(obj):  # pragma: no cover
# 
# Path: yithlibraryserver/password/models.py
# class PasswordsManager(object):
# 
#     def __init__(self, db):
#         self.db = db
# 
#     def create(self, user, password):
#         """Creates and returns a new password or a set of passwords.
# 
#         Stores the password in the database for this specific user
#         and returns a new dict with the 'owner' and '_id' fields
#         filled.
# 
#         If password is a list, do the same with each password in
#         this list.
#         """
#         if isinstance(password, dict):
#             if password:
#                 new_password = dict(password)  # copy since we are changing this object
#                 new_password['owner'] = user['_id']
#                 _id = self.db.passwords.insert(new_password, safe=True)
#                 new_password['_id'] = _id
#                 return new_password
#         else:
#             new_passwords = []  # copy since we are changing this object
#             for p in password:
#                 if p:
#                     p = dict(p)
#                     p['owner'] = user['_id']
#                     new_passwords.append(p)
# 
#             if new_passwords:
# 
#                 _ids = self.db.passwords.insert(new_passwords, safe=True)
# 
#                 for i in range(len(new_passwords)):
#                     new_passwords[i]['_id'] = _ids[i]
# 
#                 return new_passwords
# 
#     def retrieve(self, user, _id=None):
#         """Return the user's passwords or just one.
# 
#         If _id is None return the whole set of passwords for this
#         user. Otherwise, it returns the password with that _id.
#         """
#         if _id is None:
#             return self.db.passwords.find({'owner': user['_id']})
#         else:
#             return self.db.passwords.find_one({
#                     '_id': _id,
#                     'owner': user['_id'],
#                     })
# 
#     def update(self, user, _id, password):
#         """Update a password in the database.
# 
#         Return the updated password on success or None if the original
#         password does not exist.
#         """
#         new_password = dict(password)  # copy since we are changing this object
#         new_password['owner'] = user['_id']
#         result = self.db.passwords.update({
#                 '_id': _id,
#                 'owner': user['_id'],
#                 }, new_password, safe=True)
#         new_password['_id'] = _id
# 
#         # result['n'] is the number of documents updated
#         # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue
#         if result['n'] == 1:
#             return new_password
#         else:
#             return None
# 
#     def delete(self, user, _id=None):
#         """Deletes a password from the database or the whole set for this user.
# 
#         Returns True if the delete is succesfull or False otherwise.
#         """
#         query = {'owner': user['_id']}
#         if _id is not None:
#             query['_id'] = _id
# 
#         result = self.db.passwords.remove(query, safe=True)
#         return result['n'] > 0
# 
# Path: yithlibraryserver/utils.py
# def remove_attrs(dictionary, *attrs):
#     """Returns a copy of dictionary without attrs"""
#     result = {}
# 
#     for key, value in dictionary.items():
#         if key not in attrs:
#             result[key] = value
# 
#     return result


# Path: yithlibraryserver/backups/utils.py
import gzip
import json
from yithlibraryserver.compat import BytesIO
from yithlibraryserver.password.models import PasswordsManager
from yithlibraryserver.utils import remove_attrs

# 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 Affero General Public License
# along with Yith Library Server.  If not, see <http://www.gnu.org/licenses/>.




def get_user_passwords(db, user):
    passwords_manager = PasswordsManager(db)
    return [remove_attrs(password, 'owner', '_id')
            for password in passwords_manager.retrieve(user)]


def get_backup_filename(date):
    return 'yith-library-backup-%d-%02d-%02d.yith' % (
        date.year, date.month, date.day)


def compress(passwords):
    buf = BytesIO()
    gzip_data = gzip.GzipFile(fileobj=buf, mode='wb')
    data = json.dumps(passwords)
    gzip_data.write(data.encode('utf-8'))
    gzip_data.close()
    return buf.getvalue()


def uncompress(compressed_data):

    buf = BytesIO(compressed_data)