#!/usr/bin/env python3

import flask

from flask import make_response, request, redirect, jsonify, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate

db = SQLAlchemy()
app = flask.Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:m9Eb5OflQb@mysql.mysql.svc.cluster.local/subtitles'
db.init_app(app)

migrate = Migrate(app, db)

ma = Marshmallow(app)

class SubtitleEntry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    movie_id = db.Column(db.String(255), db.ForeignKey('movie.id'))
    text = db.Column(db.String(255))
    lineNumber = db.Column(db.Integer)
    startTime = db.Column(db.String(255))
    endTime = db.Column(db.String(255))


class SubtitleEntrySchema(ma.Schema):
    class Meta:
        fields = ('id', 'movie_id', 'text', 'lineNumber', 'startTime', 'endTime')
        
class Movie(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    movieName = db.Column(db.String(255))
    releaseYear = db.Column(db.String(255))
    srtPath = db.Column(db.String(255))
    moviePath = db.Column(db.String(255))
    runLength = db.Column(db.Integer)
    lastModified = db.Column(db.String(255))

class MovieSchema(ma.Schema):
    class Meta:
        fields = ('id', 'movieName', 'releaseYear', 'srtPath', 'moviePath', 'runLength', 'lastModified')

def get_links():
    links = Link.query.order_by(Link.name).all()
    schema = LinkSchema(many=True)
    link_json = schema.dump(links)
    return links

def link_exists(link_name):
    try:
        link = Link.query.filter_by(name=link_name).first()
    except Exception as e:
        print(e)
        return e
    if link is None:
        return False
    else:
        return True


@app.route('/<string:name>', strict_slashes=False, methods=['GET'])
def redirect_to_link(name):
    try:
        link = Link.query.filter_by(name=name).first()
    except e:
        return redirect("/", code=302)
    if link is None:
        return redirect("/", code=302)
    try:
        link.hit_count += 1
    except TypeError:
        link.hit_count = 1
    db.session.commit()
    print("updating link hit count")
    return redirect(link.target, code=302)


@app.post('/add', strict_slashes=False)
def add_link():
    if link_exists(request.form['link_name']) is True:
        print("Link exists")
    else:
        print("Creating link")
        db.create_all()
        link = Link(name=request.form['link_name'], target=request.form['target'], hit_count=0, owner_name="unknown")
        db.session.add(link)
        db.session.commit()
    return redirect("/", code=302)


@app.route('/<string:link_name>/add', strict_slashes=False)
def add_link_form(link_name):
    return render_template('add.html', link_name=link_name)


@app.post('/<string:link_name>/edit', strict_slashes=False)
def edit_link(link_name):
    db.create_all()
    link = Link.query.filter_by(name=link_name).first()
    print("Setting link target to {}".format(request.form['target']))
    link.target = request.form['target']
    db.session.commit()
    return redirect("/", code=302)


@app.route('/<string:link_name>/edit', strict_slashes=False)
def edit_link_form(link_name):
    link = Link.query.filter_by(name=link_name).first()
    return render_template('edit.html', link=link)


@app.post('/<int:link_id>/delete', strict_slashes=False)
def delete_link(link_id):
    link = Link.query.filter_by(id=link_id).first()
    db.session.delete(link)
    db.session.commit()
    return redirect(url_for('list_links'))


@app.route('/<int:link_id>/delete', strict_slashes=False)
def delete_link_form(link_id):
    link = Link.query.filter_by(id=link_id).first()
    return render_template('delete.html', link=link)


@app.route('/')
def list_links():
    links = get_links()
    return render_template('list.html', links=links)

#@app.route('/links/<int:id>', methods=['GET'])

if __name__ == "__main__":
    app.run(host='0.0.0.0')