# Copyright 2014 Google Inc. All rights reserved.
#
# 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
#
#     http://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.

"""Shared testing utilities."""


class _Monkey(object):
    # context-manager for replacing module names in the scope of a test.

    def __init__(self, module, **kw):
        self.module = module
        if len(kw) == 0:  # pragma: NO COVER
            raise ValueError('_Monkey was used with nothing to monkey-patch')
        self.to_restore = dict([(key, getattr(module, key)) for key in kw])
        for key, value in kw.items():
            setattr(module, key, value)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        for key, value in self.to_restore.items():
            setattr(self.module, key, value)


class _NamedTemporaryFile(object):

    def __init__(self, suffix=''):
        import os
        import tempfile
        filehandle, self.name = tempfile.mkstemp(suffix=suffix)
        os.close(filehandle)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        import os
        os.remove(self.name)


class _GAXBaseAPI(object):

    _random_gax_error = False

    def __init__(self, **kw):
        self.__dict__.update(kw)

    def _make_grpc_error(self, status_code=None):
        from grpc._channel import _RPCState
        from grpc import StatusCode
        from google.cloud.exceptions import GrpcRendezvous

        if status_code is None:
            status_code = StatusCode.UNKNOWN

        details = 'Some error details.'
        exc_state = _RPCState((), None, None, status_code, details)
        return GrpcRendezvous(exc_state, None, None, None)

    def _make_grpc_not_found(self):
        from grpc import StatusCode
        return self._make_grpc_error(StatusCode.NOT_FOUND)

    def _make_grpc_failed_precondition(self):
        from grpc import StatusCode
        return self._make_grpc_error(StatusCode.FAILED_PRECONDITION)


class _GAXPageIterator(object):

    def __init__(self, items, page_token):
        self._items = items
        self.page_token = page_token

    def next(self):
        items, self._items = self._items, None
        return items
