"""
Tests to make sure Soledad provides U1DB functionality and more.
"""

import os
import u1db
from mock import Mock


from leap.soledad import Soledad
from leap.soledad.crypto import SoledadCrypto
from leap.soledad.backends.leap_backend import (
    LeapDocument,
    decrypt_doc,
    ENC_SCHEME_KEY,
)
from leap.common.testing.basetest import BaseLeapTest


#-----------------------------------------------------------------------------
# Some tests inherit from BaseSoledadTest in order to have a working Soledad
# instance in each test.
#-----------------------------------------------------------------------------

ADDRESS = 'leap@leap.se'


class BaseSoledadTest(BaseLeapTest):
    """
    Instantiates Soledad for usage in tests.
    """

    def setUp(self):
        # config info
        self.db1_file = os.path.join(self.tempdir, "db1.u1db")
        self.db2_file = os.path.join(self.tempdir, "db2.u1db")
        self.email = ADDRESS
        # open test dbs
        self._db1 = u1db.open(self.db1_file, create=True,
                              document_factory=LeapDocument)
        self._db2 = u1db.open(self.db2_file, create=True,
                              document_factory=LeapDocument)
        # initialize soledad by hand so we can control keys
        self._soledad = self._soledad_instance(user=self.email)

    def tearDown(self):
        self._db1.close()
        self._db2.close()
        for f in [self._soledad._local_db_path, self._soledad._secrets_path]:
            if os.path.isfile(f):
                os.unlink(f)
        self._soledad.close()

    def _soledad_instance(self, user=ADDRESS, passphrase='123',
                          prefix='',
                          secrets_path=Soledad.STORAGE_SECRETS_FILE_NAME,
                          local_db_path='soledad.u1db', server_url='',
                          cert_file=None, secret_id=None):

        def _put_doc_side_effect(doc):
            self._doc_put = doc

        class MockSharedDB(object):

            get_doc = Mock(return_value=None)
            put_doc = Mock(side_effect=_put_doc_side_effect)

            def __call__(self):
                return self

        Soledad._shared_db = MockSharedDB()
        return Soledad(
            user,
            passphrase,
            secrets_path=os.path.join(self.tempdir, prefix, secrets_path),
            local_db_path=os.path.join(
                self.tempdir, prefix, local_db_path),
            server_url=server_url,  # Soledad will fail if not given an url.
            cert_file=cert_file,
            secret_id=secret_id)

    def assertGetEncryptedDoc(
            self, db, doc_id, doc_rev, content, has_conflicts):
        """
        Assert that the document in the database looks correct.
        """
        exp_doc = self.make_document(doc_id, doc_rev, content,
                                     has_conflicts=has_conflicts)
        doc = db.get_doc(doc_id)
        if ENC_SCHEME_KEY in doc.content:
            doc.set_json(decrypt_doc(self._soledad._crypto, doc))
        self.assertEqual(exp_doc.doc_id, doc.doc_id)
        self.assertEqual(exp_doc.rev, doc.rev)
        self.assertEqual(exp_doc.has_conflicts, doc.has_conflicts)
        self.assertEqual(exp_doc.content, doc.content)


# Key material for testing
KEY_FINGERPRINT = "E36E738D69173C13D709E44F2F455E2824D18DDF"
PUBLIC_KEY = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.10 (GNU/Linux)

mQINBFC9+dkBEADNRfwV23TWEoGc/x0wWH1P7PlXt8MnC2Z1kKaKKmfnglVrpOiz
iLWoiU58sfZ0L5vHkzXHXCBf6Eiy/EtUIvdiWAn+yASJ1mk5jZTBKO/WMAHD8wTO
zpMsFmWyg3xc4DkmFa9KQ5EVU0o/nqPeyQxNMQN7px5pPwrJtJFmPxnxm+aDkPYx
irDmz/4DeDNqXliazGJKw7efqBdlwTHkl9Akw2gwy178pmsKwHHEMOBOFFvX61AT
huKqHYmlCGSliwbrJppTG7jc1/ls3itrK+CWTg4txREkSpEVmfcASvw/ZqLbjgfs
d/INMwXnR9U81O8+7LT6yw/ca4ppcFoJD7/XJbkRiML6+bJ4Dakiy6i727BzV17g
wI1zqNvm5rAhtALKfACha6YO43aJzairO4II1wxVHvRDHZn2IuKDDephQ3Ii7/vb
hUOf6XCSmchkAcpKXUOvbxm1yfB1LRa64mMc2RcZxf4mW7KQkulBsdV5QG2276lv
U2UUy2IutXcGP5nXC+f6sJJGJeEToKJ57yiO/VWJFjKN8SvP+7AYsQSqINUuEf6H
T5gCPCraGMkTUTPXrREvu7NOohU78q6zZNaL3GW8ai7eSeANSuQ8Vzffx7Wd8Y7i
Pw9sYj0SMFs1UgjbuL6pO5ueHh+qyumbtAq2K0Bci0kqOcU4E9fNtdiovQARAQAB
tBxMZWFwIFRlc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zM9ooNTgbrcDzyxRkIVqsVwBq7EtzcvgYUyX53yG25Giy6YQaQ2
ZtQ/VymwFL3XdUWV6B/hU4PVAFvO3qlOtdJ6TpE+nEWgcWjCv5g7RjXX
=MuOY
-----END PGP PUBLIC KEY BLOCK-----
"""
PRIVATE_KEY = """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.10 (GNU/Linux)

[encoded data, 6336 characters]
RZXoH+FTg9UAW87eqU610npOkT6cRaBxaMK/mDtGNdc=
=JTFu
-----END PGP PRIVATE KEY BLOCK-----
"""

__all__ = [
    'test_couch',
    'test_encrypted',
    'test_leap_backend',
    'test_sqlcipher',
    'u1db_tests',
]
