# src/moddels/Blog.py

from . import db
import datetime
from marshmallow import fields, Schema


class Blog(db.Model):
    """
    Blog Model
    """
    __tablename__ = 'blogs'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text, nullable=False)
    contents = db.Column(db.Text, nullable=False)
    description = db.Column(db.Text, nullable=False)
    author_id = db.Column(
        db.Integer, db.ForeignKey('users.id'), nullable=False)
    created_at = db.Column(db.DateTime)
    modified_at = db.Column(db.DateTime)

    def __init__(self, data):
        self.title = data.get('title')
        self.contents = data.get('contents')
        self.description = data.get('description')
        self.author_id = data.get('author_id')
        self.created_at = datetime.datetime.utcnow()
        self.modified_at = datetime.datetime.utcnow()

    def save(self):
        db.session.add(self)
        db.session.commit()

    def update(self, data):
        for key, item in data.items():
            setattr(self, key, item)
        self.modified_at = datetime.datetime.utcnow()
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    @staticmethod
    def get_all_blogs():
        return Blog.query.all()

    @staticmethod
    def get_one_blog(id):
        return Blog.query.get(id)

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


class BlogSchema(Schema):
    """
    Blog Schema
    """
    id = fields.Int(dump_only=True)
    title = fields.Str(required=True)
    contents = fields.Str(required=True)
    description = fields.Str(required=True)
    author_id = fields.Int(required=True)
    created_at = fields.DateTime(dump_only=True)
    modified_at = fields.DateTime(dump_only=True)
