from flask import Flask, render_template, request, session, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import json, os
from flask_mail import Mail
from werkzeug.utils import secure_filename
import math as m

local_server = True
with open("config.json","r") as f:
    params = json.load(f)['params']

app = Flask(__name__)
app.secret_key = 'Tqrr*824'
app.config['UPLOAD_FOLDER'] = params['upload_location']
app.config.update(
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = '465',
    MAIL_USE_SSL = True,
    MAIL_USERNAME = params['gmail-user'],
    MAIL_PASSWORD = params['gmail-password']
)
mail = Mail(app)

if local_server:
    app.config["SQLALCHEMY_DATABASE_URI"] = params['local_uri']
else:
    app.config["SQLALCHEMY_DATABASE_URI"] = params['prod_uri']


db = SQLAlchemy(app)


class Contacts(db.Model):
    '''
    sno	name email date	phone_num msg
    '''
    sno = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(25), nullable=False)
    email = db.Column(db.String(30), nullable=False)
    date = db.Column(db.String(12),  nullable=True)
    phone_num = db.Column(db.String(12), nullable=False)
    msg = db.Column(db.String(120), nullable=False)
    # msg = db.Column(db.String(120), unique=False, nullable=False)


class Posts(db.Model):
    '''
    sno	title slug content date
    '''
    sno = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(25), nullable=False)
    slug = db.Column(db.String(21), nullable=False)
    content = db.Column(db.String(12),  nullable=False)
    tagline = db.Column(db.String(12),  nullable=False)
    date = db.Column(db.String(12), nullable=False)
    img_file = db.Column(db.String(20), nullable=True)

    # msg = db.Column(db.String(120), unique=False, nullable=False)


@app.route("/index")
def index():
    posts = Posts.query.filter_by().all()[0:params['no_of_posts']]
    return render_template("index.html", params=params, posts=posts)


@app.route("/")
def home():
    # Pagination logic
    posts = Posts.query.filter_by().all()
    last = m.ceil(len(posts)/params['no_of_posts'])
    page = request.args.get('page')
    if not str(page).isnumeric():
        page = 1
    page = int(page)
    posts = posts[(page-1)*int(params['no_of_posts']):(page-1)*int(params['no_of_posts'])+int(params['no_of_posts'])]
    if page == 1:
        prev = "#"
        next = "/?page="+ str(page+1)
    elif page == last:
        prev = "/?page="+ str(page-1)
        next = "#"
    else:
        prev = "/?page=" + str(page - 1)
        next = "/?page=" + str(page + 1)

    return render_template("index.html", params=params, posts=posts, prev=prev, next=next)


@app.route("/dashboard", methods=['GET','POST'])
def dashboard():

    if 'user' in session and session['user'] == params['admin_user']:
        posts = Posts.query.all()
        return render_template("dashboard.html", params=params, posts=posts)

    if request.method=='POST':
        username = request.form.get('uname')
        userpass = request.form.get('pass')
        if username == params['admin_user'] and userpass == params['admin_password']:
            # set the session variable
            session['user'] = username
            posts = Posts.query.all()
            return render_template("dashboard.html", params=params, posts=posts)

    return render_template("login.html", params=params)


@app.route("/about")
def about():
    return render_template("about.html", params=params)


@app.route("/uploader", methods=['GET','POST'])
def uploader():
    if 'user' in session and session['user'] == params['admin_user']:
        if request.method == 'POST':
            f = request.files['file1']
            f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
            return "Uploaded successfully"


@app.route("/logout")
def logout():
    session.pop('user')
    return redirect("/dashboard")


# B- A way to add a slug in url
@app.route("/post/<string:post_slug>", methods=['GET'])
def post_route(post_slug):
    post = Posts.query.filter_by(slug=post_slug).first()

    return render_template("post.html", params=params, post=post)


@app.route("/delete/<string:sno>", methods=['GET','POST'])
def delete(sno):
    if 'user' in session and session['user'] == params['admin_user']:
        post = Posts.query.filter_by(sno = sno).first()
        db.session.delete(post)
        db.session.commit()
    return redirect("/dashboard")


@app.route("/edit/<string:sno>", methods=['GET', 'POST'])
def edit(sno):
    if 'user' in session and session['user'] == params['admin_user']:
        if request.method == 'POST':
            box_title = request.form.get('title')
            tline = request.form['tline']
            slug = request.form['slug']
            content = request.form['content']
            img_file = request.form['img_file']
            if sno == '0' and img_file=='':
                post = Posts(title=box_title, tagline=tline, slug=slug, content=content, img_file="post-bg.jpg")
                db.session.add(post)
                db.session.commit()
            if sno == '0' and img_file != '':
                post = Posts(title=box_title, tagline=tline, slug=slug, content=content, img_file=img_file)
                db.session.add(post)
                db.session.commit()
            elif sno != '0':
                post = Posts.query.filter_by(sno=sno).first()
                post.title = box_title
                post.tagline = tline
                post.slug = slug
                post.content = content
                post.img_file = img_file
                db.session.commit()
                return redirect("/edit/" + sno)
        post = Posts.query.filter_by(sno=sno).first()
        return render_template("edit.html", params=params, post=post)


@app.route("/contact", methods = ['GET', 'POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        phone = request.form.get('phone')
        message = request.form.get('message')

        entry = Contacts(name=name, email=email, date=datetime.now(), phone_num=phone, msg=message)

        db.session.add(entry)
        db.session.commit()
        mail.send_message('New message from Luv ka Blog ^-^',
                          sender=params['gmail-user'],
                          recipients=[email],
                          body="Greetings "+name+"\n\nYou have been added to Luv ka blog, Have fun blogging ^-^.\n"
                               + "\n\n" + "Contact No.:\n" + "9416587326."
                          )

    return render_template("contact.html", params=params)
# In config.json all should be in double quotes.


app.run(debug=True)