# coding=utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Lorenz Hüdepohl, Emmanuel Stamou
#
# 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.

from __future__ import absolute_import
from __future__ import print_function

from .arithmetic_decorators import add_operators

def compile_errorfunction(f):
    """
    Return the compiled error propagation function

    def errorfunc(x,y,dx,dy):
        return sqrt( d_1 f * dx**2 + d_2 f * dy**2)

    for the supplied function f(x,y)
    """
    from sympy import Symbol, sqrt
    from six import exec_
    x = Symbol('x')
    dx = Symbol('dx')
    y = Symbol('y')
    dy = Symbol('dy')
    expr = f(x, y)
    err = sqrt(((expr.diff(x) * dx)**2 + (expr.diff(y) * dy)**2))
    function_code = """
def errorfunc(x, dx, y, dy):
    from math import sqrt
    return {0}
    """.format(str(err))
    env = {}
    exec_(function_code, env)
    return env["errorfunc"]

def quantity_operator(func):
    errorfunc = compile_errorfunction(func)
    def wrapped_quantity_operator(self, other):
        if not hasattr(other, "error"):
            other_value = other
            other_error = 0.0
        else:
            other_value = other.value
            other_error = other.error
        return Quantity(func(self.value, other_value), errorfunc(self.value, self.error, other_value, other_error))

    return wrapped_quantity_operator

@add_operators(quantity_operator)
class Quantity(object):
    def __init__(self, value, error):
        self.value = value
        self.error = error

    def __str__(self):
        return "{0.value}[±{0.error}]".format(self)

    def __repr__(self):
        return "Quantity({0}, {1})".format(self.value, self.error)

    def __eq__(self, other):
        return self.value == other.value and self.error == other.error