"""
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 AngularUpdate():
    def __init__(self, model):
        """
        - Arg
        model: tf.keras.Model
        """
        self.model = model
        self.kept_weights = None

    def keep_weights(self):
        """ Keeps theta_t """
        self.kept_weights = [
            tf.identity(v) for v in self.model.trainable_variables]

    def __call__(self, return_angle=True):
        """
        - Arg
        return_angle: Bool. 
          If true, returns angles; if False, returns cos(angles).
        - Returns
        angular_update: Anguar update acos(cos(theta_{t+1} \cdot theta_{t})).
        cossim: Cosine of the angular update.
        """
        # Calc angular update
        cossim = [-tf.keras.losses.cosine_similarity(
            tf.reshape(v, [-1]), tf.reshape(w, [-1])) for v,w in zip(
            self.model.trainable_variables, self.kept_weights)]

        if return_angle:
            angular_update = [tf.acos(v) for v in cossim]
            return angular_update
        else:
            return cossim


def calc_perp_para_translation(weight):
    """
    - Arg
    weight: tf.Variable. To be tf.identity()ed.
    - Returns
    thperp: tf.Tensor. Flattened. theta_perp.
        Perpendicular to grad.
    thpara: tf.Tensor. Flattened. theta_parallel.
        Perpendicular to thperp.
    """
    theta = tf.reshape(tf.identity(weight), [-1])
    dims = theta.shape[0]
    onevec = tf.constant([1]*dims, dtype=tf.keras.backend.floatx())
    thperp = tf.tensordot(theta, onevec, 1) / dims * onevec
    thpara = theta - thperp
    return thperp, thpara