"""
Copyright 2016 Deepgram

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.
"""

import logging

import numpy

from . import Layer, ParsingError

logger = logging.getLogger(__name__)

###############################################################################
class Recurrent(Layer):				# pylint: disable=too-few-public-methods
	""" A recurrent neural network.

		# Properties

		sequence: bool.
		size: int.
		bidirectional: bool.
		merge: one of (multiply, add, concat, average)
		type: one of (lstm, gru, sru)

		# Example

		```
		recurrent:
		  size: 32
		  sequence: yes
		  bidirectional: yes
		  merge: average
		  type: lstm
		```
	"""

	MERGE_TYPES = ('multiply', 'add', 'concat', 'average')
	RNN_TYPES = ('lstm', 'gru', 'sru')

	###########################################################################
	def __init__(self, *args, **kwargs):
		""" Creates a new recurrent layer.
		"""
		super().__init__(*args, **kwargs)
		self.type = None
		self.size = None
		self.sequence = None
		self.bidirectional = None
		self.merge = None

	###########################################################################
	def _parse(self, engine):
		""" Parses out the recurrent layer.
		"""
		self.sequence = engine.evaluate(self.args.get('sequence', True),
			recursive=True)
		if not isinstance(self.sequence, bool):
			raise ParsingError('Wrong type for "sequence" argument in '
				'recurrent layer. Expected bool, received: {}'
				.format(self.sequence))

		self.bidirectional = engine.evaluate(
			self.args.get('bidirectional', False),
			recursive=True
		)
		if not isinstance(self.bidirectional, bool):
			raise ParsingError('Wrong type for "bidirectional" argument in '
				'recurrent layer. Expected bool, received: {}'
				.format(self.bidirectional))

		self.merge = engine.evaluate(self.args.get('merge'), recursive=True)
		if not self.bidirectional:
			if self.merge is not None:
				raise ParsingError('Having a "merge" strategy in a '
					'"recurrent" layer only makes sense for bidirectional '
					'RNNs.')