# Import necessary classes from libraries
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, JSONResponse
import subprocess
import psutil

# Create app object
app = FastAPI()


# GET-request handler by address / (root directory)
@app.get("/", response_class=HTMLResponse)
async def index():
    return "<h1>MT5 Manager</h1>"


# POST /start handler - terminal launch
@app.post("/start")
async def start_instance():
    result = start_mt5()
    return JSONResponse(result)


# POST /stop handler - stop the terminal
@app.post("/stop", response_class=JSONResponse)
async def stop_instance():
    result = stop_mt5()
    return JSONResponse(result)


# Path to the launched terminal file
MT5_PATH = "C:/Program Files/MetaTrader 5/terminal64.exe"

# Disctionary for storing data on the launched terminal
instances = {}


# Launch the terminal
def start_mt5():
    # Launch the new process
    process = subprocess.Popen([MT5_PATH])

    # Launched process ID
    pid = process.pid

    # Save ID and process status
    instances["default"] = {"pid": pid, "status": "running"}

    # Return result - successful launch
    return {"instance": "default", "pid": pid}


# Stop the terminal
def stop_mt5():
    # If the terminal was launched previously
    if "default" in instances:
        # Take its process ID
        pid = instances["default"]["pid"]
        try:
            # Get the terminal process object
            p = psutil.Process(pid)

            # Stop the process
            p.terminate()

            # Remove data on a previously launched process
            del instances["default"]

            # Return result - successful stop
            return {"status": "stopped", "instance": "default"}
        except psutil.NoSuchProcess:
            # If the process is not found,
            # delete data on the previously launched process
            del instances["default"]

    # Return result - process not found
    return {"status": "not found", "instance": "default"}
