from flask import (
    Flask,
    render_template,
    request,
    url_for,
    redirect,
)
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200))
    created_data = db.Column(db.DateTime, default=datetime.utcnow())

    def __repr__(self):
        return "<Task %r>"%self.id

@app.route('/', methods=['GET','POST'])
def main_page():
    if request.method == 'POST':
        content_ = request.form['content']
        new_task = Todo(content=content_)
        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect('/')
        except:
            return "there was a problem to adding your task"
    else:
        tasks = Todo.query.order_by(Todo.id).all()
        return render_template('index.html', tasks=tasks)

@app.route('/delete/<int:id>')
def delete(id):
    task = Todo.query.get_or_404(id)

    try:
        db.session.delete(task)
        db.session.commit()
        return redirect('/')
    except:
        return "something went wrong"


if __name__ == "__main__":
    app.run()