 { Expression } = require './expression'
 { FunctionRef } = require './reusable'
-
+{ decimalAdjust } = require '../util/math'
 { ValueSet, Code } = require '../datatypes/datatypes'
 { build } = require './builder'
 ucum = require  'ucum'

  if a instanceof Quantity and b instanceof Quantity
    # we will choose the unit of a to be the unit we return
    val = convert_value(b.value, b.unit, a.unit)
    if val
      new Quantity({unit: a.unit, value: a.value + val})
  else
    a.copy?().add?(b.value, clean_unit(b.unit))

module.exports.doSubtraction = (a,b) ->
  if a instanceof Quantity and b instanceof Quantity
    # we will choose the unit of a to be the unit we return
    val = convert_value(b.value, b.unit, a.unit)
    if val
      new Quantity({unit: a.unit, value: a.value - val})
  else
    a.copy?().add?(b.value * -1 , clean_unit(b.unit))


  multiplyDivied: (other, operator) ->
    if other instanceof Quantity
      if @unit and other.unit
        can_val = @to_ucum() # ucum.canonicalize(@value,ucum_unit(@unit))
        other_can_value = other.to_ucum()#ucum.canonicalize(other.value,ucum_unit(other.unit))
        ucum_value = ucum_multiply(can_val,[[operator,other_can_value]])
        createQuantity(ucum_value.value, units_to_string(ucum_value.units))
      else
        value = if operator == "/" then @value / other.value  else @value * other.value
        unit = @unit || other.unit
        createQuantity(decimalAdjust("round",value,-8), unit)
    else
      value = if operator == "/" then @value / other  else @value * other
      createQuantity( decimalAdjust("round",value,-8), @unit)

  to_ucum: ->
    u = ucum.parse(ucum_unit(@unit)) # ucum.canonicalize(@value,ucum_unit(@unit))
    u.value *= @value
    u


time_unit_to_ucum = {'year' : 'a', 'month' : 'mo',  'day' : 'd' , 'hour' : 'h', 'minute' : 'min' , 'second': 's' , 'millisecond' :  'ms', 'week' : 'wk', 'weeks' : 'wk' }
