from app import app
import flask
from flask import Blueprint, render_template, request, redirect, url_for, flash
import datetime
import os
from werkzeug.utils import secure_filename
from werkzeug.datastructures import ImmutableOrderedMultiDict
import collections
from collections import OrderedDict
import dataset
import sys
import time

app.secret_key = 'PiracyIsCool'

now = datetime.datetime.now()

@app.route('/', methods=['GET'])
def index():
    return render_template("public/index.html")

@app.route("/about")
def about():
    return render_template("public/about.html")

# UPLOAD FILES
# THIS SHOULD BE IN CONFIG
app.config["BOOK_UPLOAD_DEWATERMARK"] = "/var/www/TacticalApp/app/static/dewatermark"
app.config["BOOK_UPLOAD_REPUBLISH"] = "/var/www/TacticalApp/app/static/republish"
app.config["BOOK_REQUEST"] = "/var/www/TacticalApp/app/static/request"
app.config["ALLOWED_BOOK_EXTENSIONS"] = ["PDF", "EPUB"]
app.config["MAX_BOOK_FILESIZE"] = 500000000

def allowed_book(filename):
    if not "." in filename:
        return False

    ext = filename.rsplit(".", 1)[1]

    if ext.upper() in app.config["ALLOWED_BOOK_EXTENSIONS"]:
        return True
    else:
        return False

def allowed_book_filesize(filesize):
    if int(filesize) <= app.config["MAX_BOOK_FILESIZE"]:
        return True
    else:
        return False

#Request a book
#REQUEST IN DEWATERMARK
# Link database
db = dataset.connect('sqlite:///file.db?check_same_thread=False')

# create table
table = db['requested']

@app.route('/request_form', methods=['GET'])
def request_form():
    return render_template('public/request_form.html')

# from GET /bookrequest render request.html
@app.route('/uploadbook', methods=['GET'])
def bookrequest():
    books = table.find(order_by='-id')
    return render_template('public/upload_book.html', books=books)

# from POST /submit store data in the database and forward to the request
@app.route('/submit', methods=['POST'])
def submit():
    book = dict(title=request.form['title'], author=request.form['author'], publisher=request.form['publisher'], year=request.form['year'], extention=request.form['extention'])
    table.insert(book)
    return redirect(url_for('index'))

#Request a book
#REQUEST IN REPUBLISH
# from GET /bookrequest render request.html
@app.route('/republish', methods=['GET'])
def bookrepublish():
    books = table.find(order_by='-id')
    return render_template('public/republish.html', books=books)


#Terms & Comment
# create table for comments
table_comment = db['commented']

@app.route('/write_comment', methods=['GET'])
def write_comment():
    return render_template('public/write_comment.html')

# from GET /write_comment render terms.html
@app.route('/terms', methods=['GET'])
def terms():
    comments = table_comment.find(order_by='-id')
    return render_template('public/terms.html', comments=comments)

# from POST /submit store data in the database and forward to the terms
@app.route('/submitcomment', methods=['POST'])
def submitcomment():
    comment = dict(name=request.form['name'], commenting=request.form['commenting'])
    table_comment.insert(comment)
    return redirect(url_for('terms'))


#Route to Upload, Dewatermark, and republish
@app.route("/uploadbook", methods=["GET", "POST"])
def uploadbook():

    if request.method == "POST":
        if request.files:

            #request filesize
            if not allowed_book_filesize(request.cookies.get("filesize")):
                print("File exceeded maximum size")
                return redirect(request.url)

            #demand checkbox
            if not request.form.get('match-with-pairs'):
                print("You should agree with the T&C")
                return redirect(request.url)

            book = request.files["book"]

            # confirm book has a name
            if book.filename == "":
                print("Book must have a filename")
                return redirect(request.url)

            # confirm book is the desired format
            if not allowed_book(book.filename):
                print("That book extention is not allowed")
                return redirect(request.url)

            #create a new secure filename
            else:
                filename = secure_filename(book.filename)
                basename, ext = os.path.splitext(filename)
                folder = os.path.join(app.config["BOOK_UPLOAD_DEWATERMARK"], basename)
                try:
                    os.makedirs(folder)
                except FileExistsError:
                    pass
                bookpath = os.path.join(folder, filename)
                x=2
                while os.path.exists(bookpath):
                    bookpath = os.path.join(folder, basename + "_" + str(x) + ext)
                    x+=1

                if request.method == "POST":
                    req = request.form
                    name = req["name"]
                    scan = req["scan"]
                    time = req["time"]
                    source = req["source"]
                    anecdote = req["anecdote"]

                    fieldnames = [name, scan, time, source, anecdote]
                    print(fieldnames)

                    with open((os.path.join(folder, basename) + ".txt"), 'w') as f:
                        f.write(str(fieldnames))

                book.save(bookpath)

            print("Book saved")
            # flash("Book saved")

            return redirect(request.url)

    return render_template("public/upload_book.html")

#Route to Upload and republish
@app.route("/republish", methods=["GET", "POST"])
def republish():

    if request.method == "POST":
        if request.files:

            #request filesize
            if not allowed_book_filesize(request.cookies.get("filesize")):
                print("File exceeded maximum size")
                return redirect(request.url)

            #demand checkbox
            if not request.form.get('match-with-pairs'):
                print("You should agree with the T&C")
                return redirect(request.url)

            file = request.files["book"]

            # confirm file has a name
            if file.filename == "":
                print("Book must have a filename")
                return redirect(request.url)

            # confirm book is the desired format
            if not allowed_book(file.filename):
                print("That book extention is not allowed")
                return redirect(request.url)

            #create a new secure filename
            else:
                filename = secure_filename(file.filename)
                basename, ext = os.path.splitext(filename)
                folder = os.path.join(app.config["BOOK_UPLOAD_REPUBLISH"], basename)
                try:
                    os.makedirs(folder)
                except FileExistsError:
                    pass
                filepath = os.path.join(folder, filename)
                x=2
                while os.path.exists(filepath):
                    filepath = os.path.join(folder, basename + "_" + str(x) + ext)
                    x+=1

                if request.method == "POST":
                    req = request.form
                    name = req["name"]
                    scan = req["scan"]
                    time = req["time"]
                    source = req["source"]
                    anecdote = req["anecdote"]

                    fieldnames = [name, scan, time, source, anecdote]
                    print(fieldnames)

                    with open((os.path.join(folder, basename) + ".txt"), 'w') as f:
                        f.write(str(fieldnames))

                file.save(filepath)

            print("file saved")
            # flash("file saved")

            return redirect(request.url)

    return render_template("public/republish.html")

@app.errorhandler(404)
def not_found(e):
    return render_template("public/404.html")

@app.errorhandler(500)
def not_found(e):
    return render_template("public/500.html")


# TOR BROWSER

@app.route("/covers")
def covers():
    covers = os.listdir(os.path.join(app.static_folder, "covers"))
    return render_template("public/covers.html", covers=covers)
