#!/usr/bin/env python3

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

from libraries.signalHandler import SignalHandler
from libraries.socket import ClientSocket


def printTicket(ticket):

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

    print("Id:", "".join(ticket["id"]))
    print(ticket["typeOfTicket"], "\n")

    if ticket["typeOfTicket"] == "Lotto Max":
        for i in ticket["numbers"]:
            print(*i, sep="\n")
            print("\n")
    else:
        print(*ticket["numbers"], sep="\n\n")
        print("\n")


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 = ClientSocket(ip, port)

                clientSocket.sendData()
                sockets.append(clientSocket)

                dataRecived = clientSocket.receiveData()

                print(
                    f"Client# {clientNumber + 1 } : Connection# {connectionNumber + 1}")
                printTicket(dataRecived)

            clientSocket.closeConnection()

    signal.signal(signal.SIGCHLD, SignalHandler.childSignalHandler)


if __name__ == '__main__':

    argParser = argparse.ArgumentParser()

    argParser.add_argument(
        "-c",
        "--maxConections",
        type=int,
        nargs="?",
        default=3,
        const=3,
        help="Maximum amount of connections (defualt 25).",
        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)
