# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests."""

import pytest

from google.cloud.firestore_v1beta1.gapic import firestore_client
from google.cloud.firestore_v1beta1.proto import common_pb2
from google.cloud.firestore_v1beta1.proto import document_pb2
from google.cloud.firestore_v1beta1.proto import firestore_pb2
from google.protobuf import empty_pb2


class MultiCallableStub(object):
    """Stub for the grpc.UnaryUnaryMultiCallable interface."""

    def __init__(self, method, channel_stub):
        self.method = method
        self.channel_stub = channel_stub

    def __call__(self, request, timeout=None, metadata=None, credentials=None):
        self.channel_stub.requests.append((self.method, request))

        response = None
        if self.channel_stub.responses:
            response = self.channel_stub.responses.pop()

        if isinstance(response, Exception):
            raise response

        if response:
            return response


class ChannelStub(object):
    """Stub for the grpc.Channel interface."""

    def __init__(self, responses=[]):
        self.responses = responses
        self.requests = []

    def unary_unary(self,
                    method,
                    request_serializer=None,
                    response_deserializer=None):
        return MultiCallableStub(method, self)

    def unary_stream(self,
                     method,
                     request_serializer=None,
                     response_deserializer=None):
        return MultiCallableStub(method, self)

    def stream_stream(self,
                      method,
                      request_serializer=None,
                      response_deserializer=None):
        return MultiCallableStub(method, self)


class CustomException(Exception):
    pass


class TestFirestoreClient(object):
    def test_get_document(self):
        # Setup Expected Response
        name_2 = 'name2-1052831874'
        expected_response = {'name': name_2}
        expected_response = document_pb2.Document(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                    '[ANY_PATH]')

        response = client.get_document(name)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = firestore_pb2.GetDocumentRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_get_document_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup request
        name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                    '[ANY_PATH]')

        with pytest.raises(CustomException):
            client.get_document(name)

    def test_list_documents(self):
        # Setup Expected Response
        next_page_token = ''
        documents_element = {}
        documents = [documents_element]
        expected_response = {
            'next_page_token': next_page_token,
            'documents': documents
        }
        expected_response = firestore_pb2.ListDocumentsResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                      '[ANY_PATH]')
        collection_id = 'collectionId-821242276'

        paged_list_response = client.list_documents(parent, collection_id)
        resources = list(paged_list_response)
        assert len(resources) == 1

        assert expected_response.documents[0] == resources[0]

        assert len(channel.requests) == 1
        expected_request = firestore_pb2.ListDocumentsRequest(
            parent=parent, collection_id=collection_id)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_list_documents_exception(self):
        channel = ChannelStub(responses=[CustomException()])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup request
        parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                      '[ANY_PATH]')
        collection_id = 'collectionId-821242276'

        paged_list_response = client.list_documents(parent, collection_id)
        with pytest.raises(CustomException):
            list(paged_list_response)

    def test_create_document(self):
        # Setup Expected Response
        name = 'name3373707'
        expected_response = {'name': name}
        expected_response = document_pb2.Document(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                      '[ANY_PATH]')
        collection_id = 'collectionId-821242276'
        document_id = 'documentId506676927'
        document = {}

        response = client.create_document(parent, collection_id, document_id,
                                          document)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = firestore_pb2.CreateDocumentRequest(
            parent=parent,
            collection_id=collection_id,
            document_id=document_id,
            document=document)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_create_document_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup request
        parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                      '[ANY_PATH]')
        collection_id = 'collectionId-821242276'
        document_id = 'documentId506676927'
        document = {}

        with pytest.raises(CustomException):
            client.create_document(parent, collection_id, document_id,
                                   document)

    def test_update_document(self):
        # Setup Expected Response
        name = 'name3373707'
        expected_response = {'name': name}
        expected_response = document_pb2.Document(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        document = {}
        update_mask = {}

        response = client.update_document(document, update_mask)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = firestore_pb2.UpdateDocumentRequest(
            document=document, update_mask=update_mask)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_update_document_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup request
        document = {}
        update_mask = {}

        with pytest.raises(CustomException):
            client.update_document(document, update_mask)

    def test_delete_document(self):
        channel = ChannelStub()
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                    '[ANY_PATH]')

        client.delete_document(name)

        assert len(channel.requests) == 1
        expected_request = firestore_pb2.DeleteDocumentRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_delete_document_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup request
        name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]',
                                    '[ANY_PATH]')

        with pytest.raises(CustomException):
            client.delete_document(name)

    def test_batch_get_documents(self):
        # Setup Expected Response
        missing = 'missing1069449574'
        transaction = b'-34'
        expected_response = {'missing': missing, 'transaction': transaction}
        expected_response = firestore_pb2.BatchGetDocumentsResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[iter([expected_response])])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        database = client.database_root_path('[PROJECT]', '[DATABASE]')
        documents = []

        response = client.batch_get_documents(database, documents)
        resources = list(response)
        assert len(resources) == 1
        assert expected_response == resources[0]

        assert len(channel.requests) == 1
        expected_request = firestore_pb2.BatchGetDocumentsRequest(
            database=database, documents=documents)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_batch_get_documents_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup request
        database = client.database_root_path('[PROJECT]', '[DATABASE]')
        documents = []

        with pytest.raises(CustomException):
            client.batch_get_documents(database, documents)

    def test_begin_transaction(self):
        # Setup Expected Response
        transaction = b'-34'
        expected_response = {'transaction': transaction}
        expected_response = firestore_pb2.BeginTransactionResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = firestore_client.FirestoreClient(channel=channel)

        # Setup Request
        database = client.database_root_path('[PROJECT]', '[DATABASE]')