import os
import urllib.request
from base64 import b64encode
from datetime import datetime, timedelta

from flask import Response, redirect, render_template, send_file
from app import app, db
from Models import UserModel, ClickModel, PostModel, moderator_project
from Models.AnalyticsModel import get_analytics, todays_analytics

UNPROTECTED_PATHS = ["app", "privacy_policy", "", "docs", "terms_and_conditions", "analytics", "impressum"]

swagger_ui = [
    "swaggerui/swagger-ui-bundle.js",
    "swaggerui/droid-sans.css",
    "swaggerui/swagger-ui-standalone-preset.js",
    "swaggerui/swagger-ui.css",
    "swaggerui/favicon-16x16.png",
    "swagger.json"
]
UNPROTECTED_PATHS.extend(swagger_ui)

assets = []
for path, subdirs, files in os.walk('templates/assets/'):
    for name in files:
        assets.append(os.path.join(path, name)[10:])

UNPROTECTED_PATHS.extend(assets)

ANDROID_STORE = "https://play.google.com/store/apps/details?id=com.matchinitmobile"
APPLE_STORE = "https://apps.apple.com/app/matchinit/id1615073319"
ANDROID_USER = ["android"]
APPLE_USER = ["iphone", "macintosh"]

with open("Unprotected/Flyer.png", 'rb') as f:
    flyer = str(b64encode(f.read()), "utf-8")


def check_ip(ip):
    print(ip, flush=True)
    if str(ip).startswith('141.30.') or \
            str(ip).startswith('141.56.') or \
            str(ip).startswith('141.76.'):
        return True


def handle_unprotected_request(request, path):
    if path == "app":

        ref = "None"
        if 'ref' in request.args.keys():
            ref = request.args['ref']
        click = ClickModel(ref=ref, location='app')
        db.session.add(click)
        db.session.commit()
        user_agent = request.headers.get('User-Agent').lower()
        for string in ANDROID_USER:
            if string in user_agent:
                return redirect(ANDROID_STORE)
        for string in APPLE_USER:
            if string in user_agent:
                return redirect(APPLE_STORE)

        return redirect("/#download")

    elif path == "privacy_policy":
        return render_template("privacy_policy.html")

    elif path == "terms_and_conditions":
        return render_template("terms_and_conditions.html")

    elif path == "":
        if request.method == "POST":
            name = request.form['F1']
            email = request.form['F2']
            text = request.form['F3']
            content = f'contact form:\n{name}({email}):\n{text}'
            post = PostModel(author=UserModel.matchinit_user(),
                             channel=moderator_project().channel,
                             content=content)
            db.session.add(post)
            db.session.commit()
            return render_template("thank_you.html")
        return render_template("index.html", android=ANDROID_STORE, apple=APPLE_STORE)

    elif path == "impressum":
        return render_template("impressum.html")

    elif path == "analytics":
        try:
            days = int(request.args.get("days"))
        except TypeError:
            days = 1

        analytics = [get_analytics((datetime.today()-timedelta(days=1+i)).date()) for i in range(days)]
        current_anaytics = todays_analytics()
        all_clicks = db.session.query(ClickModel.ref, db.func.count(ClickModel.ref)).group_by(ClickModel.ref).all()
        todays_clicks = db.session.query(ClickModel.ref, db.func.count(ClickModel.ref))\
            .filter(ClickModel.time >= datetime.utcnow().date()).group_by(ClickModel.ref).all()
        if not todays_clicks:
            todays_clicks = [("None", 0)]

        return render_template("analytics.html",
                               analytics=analytics,
                               current_anaytics=current_anaytics,
                               all_clicks=all_clicks,
                               todays_clicks=todays_clicks)

    elif path == "assets/counter.css":
        return Response(render_template('assets/counter.css',
                                        count=db.session.query(UserModel).count()), content_type="text/css")

    elif path in assets:
        return send_file('templates/'+path)

    elif path == "docs":
        docs = urllib.request.Request("http://api_server.local")
        try:
            response = urllib.request.urlopen(docs).read()
        except Exception as e:
            response = app.response_class(
                response='{\n    "response": "' + str(e) + '"\n}',
                status=502,
                mimetype='application/json'
            )
            return response
        return response

    else:
        req = urllib.request.Request(f"http://api_server.local/{path}")
        try:
            request = urllib.request.urlopen(req)
            response = Response(
                request.read(),
                headers=dict(request.info())
            )
            return response
        except Exception as e:
            response = app.response_class(
                response='{\n    "response": "' + str(e) + '"\n}',
                status=502,
                mimetype='application/json'
            )
            return response
