import os
import time

from quixote import get_publisher
from wcs.qommon.storage import StorableObject
from wcs.qommon import misc

class StrongboxType(StorableObject):
    _names = 'strongbox-types'

    id = None
    label = None
    validation_months = 0


class StrongboxFile():
    id = None
    orig_filename = None
    base_filename = None
    content_type = None
    charset = None

    def __init__(self, id, f):
        self.id = id
        self.orig_filename = f.orig_filename
        self.base_filename = f.base_filename
        self.content_type = f.content_type
        self.charset = f.charset
        self.fp = f.fp

    def __getstate__(self):
        odict = self.__dict__.copy()
        if not odict.has_key('fp'):
            return odict

        # XXX: add some locking
        del odict['fp']
        dirname = os.path.join(get_publisher().app_dir, 'strongbox-files')
        if not os.path.exists(dirname):
            os.mkdir(dirname)
        odict['filename'] = os.path.join(dirname, str(self.id))
        self.fp.seek(0)
        fd = file(odict['filename'], 'w')
        fd.write(self.fp.read())
        fd.close()
        return odict


class StrongboxItem(StorableObject):
    _names = 'strongbox-items'
    _hashed_indexes = ['user_id']

    user_id = None
    description = None
    file = None
    type_id = None
    expiration_time = None
    proposed_by = None
    proposed_time = None
    validated_time = None

    def get_display_name(self):
        if self.description:
            return self.description
        return self.file.base_filename

    def set_file(self, file):
        self.file = StrongboxFile(self.id, file)

    def remove_file(self):
        os.unlink(self.file.filename)

    def set_expiration_time_from_date(self, value):
        if not value:
            self.expiration_time = None
            return
        if not StrongboxType.has_key(self.type_id):
            return

        if not StrongboxType.get(self.type_id).validation_months:
            self.expiration_time = None
            return

        date = time.strptime(value, misc.date_format())
        year, month, day = date[:3]
        month += StrongboxType.get(self.type_id).validation_months
        while month > 12:
           year += 1
           month -= 12
        while True:
            try:
                self.expiration_time = time.strptime(
                       '%04d-%02d-%02d' % (year, month, day), '%Y-%m-%d')
            except ValueError:
                day -= 1
                continue
            break

