import sys
import os
import signal
import psutil
import socket
import time
import threading
import requests
import json


def writeTracebackToFile(filepath, traceback):
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(traceback)


def writePortToFile(filepath, port):
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(json.dumps({'port': port}))
        

def getNewPort():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 0))
    port = sock.getsockname()[1]
    sock.close()
    return port


def isRunning(pid):
    if not psutil.pid_exists(pid):
        os.kill(os.getpid(), signal.SIGTERM)


class setInterval:
    def __init__(self, interval, action, param):
        self.interval = interval
        self.action = action
        self.param = param
        self.stopEvent = threading.Event()
        thread = threading.Thread(target=self.__setInterval, daemon=True)
        thread.start()

    def __setInterval(self):
        nextTime = time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()):
            nextTime += self.interval
            self.action(self.param)

    def cancel(self):
        self.stopEvent.set()


def isServerListening(port):
    try:
        response = requests.get(
            f'https://localhost:{port}/alive', verify=False)
        return response.ok
    except:
        return False


def writePortToFileWhenServerIsListening(port):
    while not isServerListening(port):
        time.sleep(0.1)
    writePortToFile(sys.argv[1], port)
