# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Implementations of interoperability test methods."""

import enum
import json
import os
import threading
import time

from oauth2client import client as oauth2client_client

import grpc
from grpc.beta import implementations

from src.proto.grpc.testing import empty_pb2
from src.proto.grpc.testing import messages_pb2
from src.proto.grpc.testing import test_pb2


class TestService(test_pb2.TestServiceServicer):

  def EmptyCall(self, request, context):
    return empty_pb2.Empty()

  def UnaryCall(self, request, context):
    if request.HasField('response_status'):
      context.set_code(request.response_status.code)
      context.set_details(request.response_status.message)
    return messages_pb2.SimpleResponse(
        payload=messages_pb2.Payload(
            type=messages_pb2.COMPRESSABLE,
            body=b'\x00' * request.response_size))

  def StreamingOutputCall(self, request, context):
    if request.HasField('response_status'):
      context.set_code(request.response_status.code)
      context.set_details(request.response_status.message)
    for response_parameters in request.response_parameters:
      yield messages_pb2.StreamingOutputCallResponse(
          payload=messages_pb2.Payload(
              type=request.response_type,
              body=b'\x00' * response_parameters.size))

  def StreamingInputCall(self, request_iterator, context):
    aggregate_size = 0
    for request in request_iterator:
      if request.payload is not None and request.payload.body:
        aggregate_size += len(request.payload.body)
    return messages_pb2.StreamingInputCallResponse(
        aggregated_payload_size=aggregate_size)

  def FullDuplexCall(self, request_iterator, context):
    for request in request_iterator:
      if request.HasField('response_status'):
        context.set_code(request.response_status.code)
        context.set_details(request.response_status.message)
      for response_parameters in request.response_parameters:
        yield messages_pb2.StreamingOutputCallResponse(
            payload=messages_pb2.Payload(
                type=request.payload.type,
                body=b'\x00' * response_parameters.size))

  # NOTE(nathaniel): Apparently this is the same as the full-duplex call?
  # NOTE(atash): It isn't even called in the interop spec (Oct 22 2015)...
  def HalfDuplexCall(self, request_iterator, context):
    return self.FullDuplexCall(request_iterator, context)


def _large_unary_common_behavior(
    stub, fill_username, fill_oauth_scope, call_credentials):
  request = messages_pb2.SimpleRequest(
      response_type=messages_pb2.COMPRESSABLE, response_size=314159,
      payload=messages_pb2.Payload(body=b'\x00' * 271828),
      fill_username=fill_username, fill_oauth_scope=fill_oauth_scope)
  response_future = stub.UnaryCall.future(
      request, credentials=call_credentials)
  response = response_future.result()
  if response.payload.type is not messages_pb2.COMPRESSABLE:
    raise ValueError(
        'response payload type is "%s"!' % type(response.payload.type))
  elif len(response.payload.body) != 314159:
    raise ValueError(
        'response body of incorrect size %d!' % len(response.payload.body))
  else:
    return response


def _empty_unary(stub):
  response = stub.EmptyCall(empty_pb2.Empty())
  if not isinstance(response, empty_pb2.Empty):
    raise TypeError(
        'response is of type "%s", not empty_pb2.Empty!', type(response))


def _large_unary(stub):
  _large_unary_common_behavior(stub, False, False, None)


def _client_streaming(stub):
  payload_body_sizes = (27182, 8, 1828, 45904,)
  payloads = (
      messages_pb2.Payload(body=b'\x00' * size)
      for size in payload_body_sizes)
  requests = (
      messages_pb2.StreamingInputCallRequest(payload=payload)
      for payload in payloads)
  response = stub.StreamingInputCall(requests)
  if response.aggregated_payload_size != 74922:
    raise ValueError(
        'incorrect size %d!' % response.aggregated_payload_size)


def _server_streaming(stub):
  sizes = (31415, 9, 2653, 58979,)

  request = messages_pb2.StreamingOutputCallRequest(
      response_type=messages_pb2.COMPRESSABLE,
      response_parameters=(
          messages_pb2.ResponseParameters(size=sizes[0]),