"""
MIT License

Copyright (c) 2022 Author(s)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import tensorflow as tf

class SmallModel(tf.keras.Model):
    """ It's a small model. 
    linear, Act(swish), linear, BN, linear, loss.
    """
    def __init__(
        self, 
        num_classes,
        units=[128, 128],
        ):
        """
        Comment: 
        tf.keras.backend.floatx() should be "float64". 
        Set tf.keras.backend.set_floatx("float64").
        Args:
        num_classes: The number of classes used as labels.
        units: A list of integers.
        """
        super(SmallModel, self).__init__(name="SmallModel")

        # Initialize
        self.num_classes = num_classes
        self.units = units
        self.floatx = tf.keras.backend.floatx()
        self.epsilon = tf.keras.backend.epsilon()

        # Initial checks: dtype
        if self.floatx != "float64":
            print("WARNING: tf.keras.backend.floatx is not 'float64'."+\
                " Got {}.".format(self.floatx))

        # Construct layers
        #####################################################
        self.dense0 = tf.keras.layers.Dense(
            units=self.units[0], activation=None, use_bias=False)
        self.act0 = tf.keras.layers.Activation("swish")
        self.dense1 = tf.keras.layers.Dense(
            units=self.units[1], activation=None, use_bias=False)
        self.bn0 = tf.keras.layers.BatchNormalization(
            epsilon=self.epsilon, # default epsilon=1e-7. BN default=0.001 
            trainable=False, # to ensure scale-invariance
            axis=-1, momentum=0.99, center=True, scale=True,
            beta_initializer='zeros', gamma_initializer='ones',
            moving_mean_initializer='zeros', 
            moving_variance_initializer='ones',
            beta_regularizer=None, gamma_regularizer=None, 
            beta_constraint=None,
            gamma_constraint=None, renorm=False, 
            renorm_clipping=None, renorm_momentum=0.99,
            fused=None, virtual_batch_size=None, adjustment=None)
        self.dense2 = tf.keras.layers.Dense(
            units=self.num_classes, activation=None, use_bias=False)

    def call(self, inputs):
        """
        Args:
        inputs: A Tensor representing a batch of input images.
        Returns:
        Logits with shape [batch size, self.num_classes].
        """
        x = self.dense0(inputs)
        x = self.act0(x)
        x = self.dense1(x)
        x = self.bn0(x, training=False) # for scale-invariance
        bottleneck = tf.identity(x, "bottleneck")
        logits = self.dense2(x)

        return logits, bottleneck