#      _                   _ _
#  _____| |__ ___ _ __  _ __(_| |___ _ _
# (_-/ _` / _/ _ | '  \| '_ | | / -_| '_|
# /__\__,_\__\___|_|_|_| .__|_|_\___|_|
#                      |_|
# Copyright (c) 2013-2016 transentis management & consulting. All rights reserved.
#



{{{header}}}

class simulation_model():
  def memoize(self, equation, arg):
    mymemo = self.memo[equation]
    if arg in mymemo.keys():
      return mymemo[arg]
    else:
      result = self.equations[equation](arg)
      mymemo[arg] = result

    return result

  def __init__(self):
    # Simulation Buildins
    self.dt = {{specs.dt}}
    self.starttime = {{specs.start}}
    self.stoptime = {{specs.stop}}
    self.equations = {
  	# Stocks {{#each stocks}}
  		'{{{name}}}': lambda t : {{{expression}}},
  	{{/each}}
    # flows {{#each flows}}
  		'{{{name}}}': lambda t : {{{expression}}},
  	{{/each}}	# converters {{#each converters}}
  		'{{{name}}}': lambda t : {{{expression}}},
  	{{/each}}
    # gf {{#each gf}}
  		'{{{name}}}': lambda t : LERP({{{expression}}},self.points['{{{name}}}']),
  	{{/each}}
    #constants
    {{#each constants}}
  		'{{{name}}}': lambda t : {{{expression}}}
      ,
  	{{/each}}
    }

    self.points = {
  	{{#each gf}}	'{{{name}}}': [ {{#each points}}{{#if @index}},{{/if}}[{{{this}}}]{{/each}} ],
  	{{/each}} }

    self.dimensions = {
  	{{#each dimensions}}	'{{{name}}}': {
  			'labels': [ {{#each labels}}{{#if @index}},{{/if}}'{{{this}}}'{{/each}} ],
  			'variables': [ {{#each variables}}{{#if @index}},{{/if}}'{{{name}}}'{{/each}} ]
  		},
  	{{/each}} }

    self.stocks = [{{#each stocks}}{{#if @index}},{{/if}}'{{{name}}}'{{/each}}]
    self.flows = [{{#each flows}}{{#if @index}},{{/if}}'{{{name}}}'{{/each}}]
    self.converters = [{{#each converters}}{{#if @index}},{{/if}}'{{{name}}}'{{/each}}]
    self.gf = [{{#each gf}}{{#if @index}},{{/if}}'{{{name}}}'{{/each}}]
    self.constants= [{{#each constants}}{{#if @index}},{{/if}}'{{{name}}}'{{/each}}]
    self.events = [{{#each events}}{{#if @index}},{{/if}}
    		{ 'key':'{{entity}}','threshold':{{threshold}},'direction':'{{{direction}}}','repeat':'{{repeat}}','interval':{{interval}},'messages':[{{#each messages}}{{#if @index}},{{/if}}{ 'message':'{{message}}','action':'{{action}}'}{{/each}}]}{{/each}}
    	]

    self.memo = {}
    for key in list(self.equations.keys()):
      self.memo[key] = {}  # DICT OF DICTS!

  def specs(self):
    return self.starttime, self.stoptime, self.dt, '{{specs.units}}', '{{specs.method}}'

  def setDT(self,v):
    self.dt = v

  def setStarttime(self,v):
    self.starttime = v

  def setStoptime(self,v):
    self.stoptime = v
