"""
    Service class
    Install InfoWS as windows service so we can have
    autostart with windows and stop and restart
"""

import logging
import logging.handlers
import os
import socket
import sys

script_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_path)
sys.path.insert(0, script_path+'\\modules\\libs.zip')
sys.path.insert(0, script_path+'\\modules')
sys.path.insert(0, script_path)
sys.path.append(os.path.dirname(__name__))

from multiprocessing import Process

import servicemanager
import win32event
import win32service
import win32serviceutil
from server import read_config_file, start_server


class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = "ApiWebServer-Service3"
    _svc_display_name_ = "ApiWebServer Service3"

    def __init__(self, *args):
        win32serviceutil.ServiceFramework.__init__(self, *args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(6000)
        self.list_servers = [Process(target = start_server, name=f"InfoWS_Server_{port}", args = (port, )) 
                             for port in read_config_file()["infows_port"]]
        self.stop_requested = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        for proc in self.list_servers:
            proc.terminate()
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        self.stop_requested = True

    def SvcDoRun(self):
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE, 
            servicemanager.PYS_SERVICE_STARTED, 
            (self._svc_name_, '')
        )
        self.main()
        # win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
 
    def main(self):
        for proc in self.list_servers:
            proc.start()

        for proc in self.list_servers:
            proc.join()


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(Service)
