# w.c.s. - web application for online forms
# Copyright (C) 2005-2010  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import random
import string

from .storage import StorableObject
import time

class Token(StorableObject):
    _names = 'tokens'

    type = None
    expiration = None

    def __init__(self,
            expiration_delay = 86400,
            size = 16,
            chars = list(string.digits + string.ascii_letters)):
        StorableObject.__init__(self, self.get_new_id(size, chars))
        if expiration_delay:
            self.expiration = time.time() + expiration_delay

    @classmethod
    def get_new_id(cls, size, chars):
        r = random.SystemRandom()
        while True:
            id = ''.join([r.choice(chars) for x in range(size)])
            if not cls.has_key(id):
                return id

    def migrate(self):
        if self.expiration and self.expiration < time.time():
            self.remove_self()
            raise KeyError()
