from app import db
from datetime import datetime
import re


def slugify(s):
	pattern = r'[^\w+]'
	return re.sub(pattern, '-', s)


# create relationships many to many
post_tags = db.Table('post_tags', 
			db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
			db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),

			)





class Post(db.Model):
	id = db.Column(db.Integer, primary_key=True)
	title = db.Column(db.String(140))
	slug = db.Column(db.String(140), unique=True)
	body = db.Column(db.Text)
	created = db.Column(db.DateTime, default=datetime.now())

	def __init__(self, *args, **kwargs):
		super(Post, self).__init__(*args, **kwargs)
		self.generate_slug()

	# part to relationships many to many
	tags = db.relationship('Tag', secondary=post_tags, backref=db.backref('posts'), lazy='dynamic')


	def generate_slug(self):
		if self.title:
			self.slug = slugify(self.title)

	def __repr__(self):
		return '<Post id: {}, title: {}>'.format(self.id, self.title)


class Tag(db.Model):
	id = db.Column(db.Integer, primary_key=True)
	tag_name = db.Column(db.String(100)) 
	tag_slug = db.Column(db.String(100)) 

	def __init__(self, *args, **kwargs):
		super(Tag, self).__init__(*args, **kwargs)
		self.tag_slug = slugify(self.tag_name)

	def __repr__(self):
		return '<Tag id: {}, tag_name: {}>'.format(self.id, self.tag_name)




class Currency(db.Model):
	id = db.Column(db.Integer, primary_key = True)
	currency_name = db.Column(db.String(100))
	currency_value = db.Column(db.Float)
	currency_date = db.Column(db.DateTime, default=datetime.now())

	def __init__(self, *args, **kwargs):
		super(Currency, self).__init__(*args, **kwargs)


	def __repr__(self):
		return '<currency id: {}, currency_name: {}>'.format(self.id, self.currency_name)













