#!/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

import argparse

db = SQLAlchemy()
app = flask.Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:m9Eb5OflQb@mysql.mysql.svc.cluster.local/gopy'
db.init_app(app)
list_fqdn = "https://go.dezendorf.net/list"

migrate = Migrate(app, db)

ma = Marshmallow(app)

class Link(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=True)
    target = db.Column(db.String(255))
    hit_count = db.Column(db.Integer)
    owner_name = db.Column(db.String(255))

    def __repr__(self):
        return '<Link id=(id) name=(name) target=(target)>'.format(
            id=self.id, name=self.name, target=self.target, hit_count=self.hit_count, owner_name=self.owner_name
        )

class LinkSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'target', 'hit_count', 'owner_name')

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(list_fqdn)
    if link is None:
        return redirect(list_fqdn)
    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(list_fqdn)


@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(list_fqdn)


@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(list_fqdn)


@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('/list')
def list_links():
    #app.logger.info("Base URL: {}".format(request.base_url))
    #if "http://" in request.base_url:
    #    app.logger.info("redirecting /list URL: {} to {}".format(request.base_url, list_fqdn))
    #    return redirect(list_fqdn)
    links = get_links()
    return render_template('list.html', links=links, request=request)


@app.route('/')
def landing_page():
    return redirect(list_fqdn)


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