from pathlib import Path
from flask import request, Flask
from flask_cors import CORS
from datetime import datetime
import pyodbc
import subprocess


app = Flask(__name__)
# cors = CORS(app, resources={r"/*": {"origins": "http://localhost:4200/"}})
CORS(app)

script_dir = Path(__file__).parent
batch_dir = script_dir.joinpath('../batch').resolve()
print(batch_dir)
tasks_dir = script_dir.joinpath('../../Tasks').resolve()
if not tasks_dir.exists():
    tasks_dir = script_dir.joinpath('../../Portal/Tasks').resolve()
print(tasks_dir)
# batch_dir = Path('C:/GAPS/GCStarter/batch')
# path2 = Path('C:/GAPS/Portal/Tasks')


@app.route('/', methods=['GET', 'POST'])
def main():
    if request.args.get('valid') != '1':
        return "Funktioniert!"

    if request.args.get('gchr') is not None:
        return gchr()

    log = request.args.get('log')
    if log is not None:
        return logs(log)

    filename = request.args.get('batch', 'GCStarter.bat')
    return batch(filename)


@app.route('/gchr/', methods=['POST'])
def gchr():
    dsn = request.form.get('dsn')
    query = request.form.get('query')
    if dsn is None or query is None:
        return 'Fehler: fehlende Parameter'
    return fetch_query_as_csv(dsn[5:], query)


def fetch_query_as_csv(dsn, query):
    try:
        conn = pyodbc.connect(dsn)
        cursor = conn.cursor()
        cursor.execute(query)
        return "\r\n".join([";".join(map(str, row)) for row in cursor.fetchall()])
    except pyodbc.InterfaceError as e:
        print(e.args[1])
        return e.args[1], 422


@app.route('/logs/<log>')
def logs(log):
    logfile = batch_dir.joinpath('logs/' + log)
    if not logfile.exists():
        return f"Fehler: Datei '{log}' unbekannt"
    with open(logfile, 'r') as f:
        return f.read()


@app.route('/batch/<filename>')
def batch(filename):
    cmd = batch_dir.joinpath(filename)
    if not cmd.exists():
        cmd = tasks_dir.joinpath(filename)
    if not cmd.exists():
        return f"Fehler: Datei '{filename}' unbekannt"
    log = filename[:-4] + '_' + datetime.now().strftime('%Y%m%d_%H%M%S') + '.log'
    logfile = batch_dir.joinpath('logs/' + log)

    with open(logfile, 'wb') as stream:
        if filename != 'GCStarter.bat':
            stream.write(b'Starte Prozess...')
            cmd = str(cmd) + ' & echo Prozess beendet. & echo [.]'
        subprocess.Popen(f'C:\\Windows\\System32\\cmd.exe /C "{cmd}"', stdout=stream, stderr=stream)
        # p.wait()
    return log


if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8091')
