# -*- coding: utf-8 -*-

# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from calvin.actor.actor import Actor, manage, condition, stateguard, calvinsys


class DelayToken(Actor):
    """
    Sends input on after a given delay has passed.

    Input :
        token : anything
    Outputs:
        token : anything
    """

    @manage(['delay'])
    def init(self, delay):
        self.delay = delay
        self.timers = []
        self.setup()

    def setup(self):
        self._timer = calvinsys.open(self, "sys.timer.once")

    def _new_timer(self):
        timer = calvinsys.open(self, "sys.timer.once")
        calvinsys.write(timer, self.delay)
        return timer
        
    def will_migrate(self):
        for tokens in self.timers:
            calvinsys.close(tokens['timer'])

    def did_migrate(self):
        self.setup()

    @condition(['token'])
    def token_available(self, token):
        self.timers.append({'token': token, 'timer': self._new_timer()})
        

    @stateguard(lambda self: len(self.timers) > 0 and calvinsys.can_read(self.timers[0]['timer']))
    @condition([], ['token'])
    def timeout(self):
        o = self.timers.pop(0)
        calvinsys.read(o['timer'])
        return (o['token'], )

    action_priority = (timeout, token_available)
    requires = ['sys.timer.once']

@@ -762,17 +762,62 @@
  passed.
+ NOTE: Migration will currently reset timers.
 %0A
-
 %0A    Inp
@@ -913,16 +913,26 @@
 %5B'delay'
+, 'timers'
 %5D)%0A    d
@@ -1060,59 +1060,80 @@
     
+for token in 
 self.
-_
 timer
- = calvinsys.open(self, %22sys.timer.once%22
+s: %0A            token%5B'timer'%5D = self._new_timer(
 )%0A%0A 
@@ -1392,16 +1392,51 @@
 timer'%5D)
+%0A            tokens%5B'timer'%5D = None
 %0A%0A    de
@@ -1785,17 +1785,20 @@
         
-o
+item
  = self.
@@ -1834,17 +1834,20 @@
 ys.read(
-o
+item
 %5B'timer'
@@ -1865,17 +1865,20 @@
 return (
-o
+item
 %5B'token'

manage delayed tokens during migration