from yasi_applets.install import bp
from flask import Flask, request, session, redirect, \
     url_for, render_template, flash, Blueprint, jsonify
from flask import current_app

import subprocess
import threading


status = {
    "status": "idle",  # idle | running | finished
    "output": "",
    "exit_code": None,
    "lines": []
}


@bp.route('/install',methods=['GET', 'POST', 'PUT'])
def install_index():
    """
    The page you'd get if you access the root of
    this app in a browser.
    """
    install_start()
    return render_template('install.html')


@bp.route('/install-start',methods=['GET', 'POST', 'PUT'])
def install_start():
    """
    Trigger the installation process
    """
    print("The installation process is starting!... in theory at least")
    if status["status"] == "running":
        return jsonify({"status": "already running"}), 409  # Conflict
    threading.Thread(target=run_script).start()
    return jsonify({"status": "started"})
    print("did it finish?")


def run_script():
    global status
    status["status"] = "running"

    process = subprocess.Popen(
        ["bash", "/data/jonathan/devel/highvoltage/system-installer/daemon/src/fake-install-shell.sh"],
        stdout = subprocess.PIPE,
        stderr = subprocess.STDOUT,
        text = True)

    lines = []
    for line in iter(process.stdout.readline,''):
        #lines.append(line.strip())
        #status["output"] = "\n".join(lines)
        status["lines"].append(line.strip())

    process.wait()
    status["status"] = 'finished'
    status["exit_code"] = process.returncode

    print(lines)
    print("status:", status["status"], "code:", status["exit_code"])


@bp.route('/install/status', methods=['GET', 'POST'])
def install_status():
    """
    Update on the status of the installation process.
    """

    # Keep track of the last line posted, so that we can include
    # any new lines not provided to the UI yet
    last_line = int(request.args.get("last_line", 0))
    new_lines = status["lines"][last_line:]

    if not new_lines and status["status"] == "finished":
        return ""  # Empty response = HTMX will stop polling

    lines_html = ""
    for i, line in enumerate(new_lines, start=last_line + 1):
        lines_html += f'<div>{line}</div>'

    return {
        "output": status['output'],
        "status": status['status'],
	"lines": lines_html,
        "last_line": f'<input type="hidden" id="last-line" name="last_line" value="{last_line + len(new_lines)}">'
    }


@bp.route('/install/cancel', methods=["POST"])
def install_cancel():
    """
    Cancel the installation process.
    """
    if status["status"] != "running" or not status["process"]:
        return Response("No running script", status=400)
    process["process"].terminate()
    process["status"] = "cancelled"
    process["exit_code"] = -1
    return Response("Cancelled", status=200)


@bp.route('/settings',methods=['GET', 'POST', 'PUT'])
def settings():
    """
    Manage settings for the installation module.
    """
    print("Settings")
