#!/usr/bin/python
"""
               #   # ####  ##### #   # ##### #   # #   #
               #  #  #   # #     ## ##  #  # #  ## #   #
               ###   ####  ####  # # #  #  # # # # #####
               #  #  #     #     #   #  #  # ##  # #   #
               #   # #     ##### #   # #   # #   # #   #

                   Kremlin Magical Everything System
               Glasnost Image Board and Boredom Inhibitor

"""
from datetime import datetime
import hashlib

from flaskext.sqlalchemy import SQLAlchemy

from kremlin import app

# FIXME: temporary, for dev purposes. Move me to __init__.py
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test.db'
db = SQLAlchemy(app)


class Users(db.Model):
    """ Declarative class for Users database table """
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

class Posts(db.Model):
    """ Declarative class for Posts database table """
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    # Foreign key for image attached to post
    # :relationaldatabases:
    image_id = db.Column(db.Integer, db.ForeignKey('images.id'))
    image = db.relationship('Images',
        backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, image, title=None, body=None, pub_date=None):
        self.image = image
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date

    def __repr__(self):
        return '<Post %r>' % self.title

class Images(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.String(50)
    sha1sum = db.String(40) # 40 bytes - lenght of a SHA1 hexadecimal digest

    def __init__(self, name, filedata):
        self.name = name

        h = hashlib.new('sha1')
        h.update(filedata)
        self.sha1sum = h.hexdigest()

    def __repr__(self):
        return '<Image with checksum %r>' % self.sha1sum



@@ -1943,16 +1943,26 @@
  name = 
+db.Column(
 db.Strin
@@ -1966,16 +1966,17 @@
 ring(50)
+)
 %0A    sha
@@ -1989,67 +1989,58 @@
  db.
-String(40) # 40 bytes - lenght of a SHA1 hexadecimal digest
+Column(db.String(40), unique=True) # 40 bytes SHA1
 %0A%0A  

Fix Images table columns, make SHA1 unique