import os
import signal
import sys
import time

# import panel as pn

# Daemonize Bankr App (on Linux)


def bankr_app_sim():
    while True:  # Simulation of Panel Server: https://panel.holoviz.org/how_to/server/multiple.html
        print("Bankr App is running...")
        time.sleep(10)


# def bankr_app():
#     # signal.signal(signal.SIGTERM, stop_app)
#     pn.serve({
#         'markdown': f"# This is a Panel app in {__name__}",
#         'json': pn.pane.JSON({'name': f"{__name__}"})
#     })


# Reaktion auf Signals: https://www.furkanbaytekin.dev/blogs/software/linux-signals-and-process-management-tools


def start_app():
    if os.fork():  # End parent process...
        sys.exit(0)
    os.setsid()  # ... and set new one, disconnected from terminal
    with open(".bankr_app.pid", "w") as f:
        f.write(str(os.getpid()) + "\n")
    bankr_app_sim()  # Run app in this process after saving the pid


def stop_app():
    with open(".bankr_app.pid", "r") as f:
        pid = int(f.read().strip())
    os.kill(pid, signal.SIGTERM)
    if os.path.exists(".bankr_app.pid"):
        os.remove(".bankr_app.pid")
    print("Ende Stop-App")


# ----------------------------------------

# Version mit daemonize

# pip install python-daemon

# import time
# from daemon import DaemonContext

# def bankr_app():
#     while True:
#         print("Bankr App is running...")
#         time.sleep(15)

# def start_app():
#     with DaemonContext(), open('.bankr_app.pid', 'w') as f:
#         f.write(str(os.getpid()) + '\n')
#         bankr_app()


# ----------------------------------------

# Version für Windows

# pip install pywin32

# import win32serviceutil
# import win32service
# import servicemanager

# class PanelServeService(win32serviceutil.ServiceFramework):
#     _svc_name_ = "PanelServeService"  # The name your service will have in the SCM
#     _svc_display_name_ = "Panel Serve Service"  # The display name when browsing for services

#     def __init__(self, args):
#         win32serviceutil.ServiceFramework.__init__(self, args)

#     def SvcStop(self):
#         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#         # Add your stop actions here

#     def SvcDoRun(self):
#         servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
#                               servicemanager.PYS_SERVICE_STARTED,
#                               (self._svc_name_, ''))
#         self.main()  # You can put your main server-like functionality here or call a function that does it

# def main():
#     if __name__ == '__main__':
#         win32serviceutil.HandleCommandLine(PanelServeService)
