#!/usr/bin/env python3

import argparse
import random
import signal
import errno
import json
import os
from socket import *


def printTicket(ticket):

    with open("prediction.json", "a") as writeToFile:
        json.dump(ticket, writeToFile)

    print(*ticket["numbers"], sep="\n\n")
    print("\n")


def sendRequest(clientSocket):

    typeOfTicket = 2
    numberOfTickets = 1

    dataToSend = dict(
        typeOfTicket=typeOfTicket,
        numberOfTickets=numberOfTickets)
    clientSocket.sendall(str(dataToSend).encode())


def zombieSlayer(signalNumber, frame):

    while True:
        try:
            pid, status = os.waitpid(-1, os.WNOHANG)

        except OSError:
            return

    if pid == 0:
        return


def main(maxConnections, maxClients):

    ip = "localhost"
    port = 8080
    sockets = []

    for clientNumber in range(maxClients):
        try:
            pid = os.fork()
        except OSError:
            sys.stderr.write("Could not fork() a child")
            continue

        if pid == 0:
            for connectionNumber in range(maxConnections):

                clientSocket = socket(AF_INET6, SOCK_STREAM)
                clientSocket.connect((ip, port))
                sendRequest(clientSocket)
                sockets.append(clientSocket)

                dataRecived = eval(clientSocket.recv(1000).decode())

                print(f"\nHere is your prediction for this weeks Lotto 6/49\n")
                printTicket(dataRecived)

                os._exit(0)

    signal.signal(signal.SIGCHLD, zombieSlayer)


if __name__ == '__main__':

    argParser = argparse.ArgumentParser()

    argParser.add_argument(
        "-c",
        "--maxConections",
        type=int,
        nargs="?",
        default=1,
        const=1,
        help="Maximum amount of connections (defualt 1).",
        dest="maxConnections")

    argParser.add_argument(
        "-n",
        "--maxClients",
        type=int,
        nargs="?",
        default=1,
        const=1,
        help="Maximum amount of clients (default 1).",
        dest="maxClients")

    switches = argParser.parse_args()

    main(switches.maxConnections, switches.maxClients)
