import os

from src import Worker
from os import getenv
from multiprocessing import Pool, Queue, Process, Manager
import csv
import json
from src.logger import listener_process, listener_configurer, worker_configurer


def setup_logins_ports():
    manager = Manager()
    shared_ip_list = manager.list(
        [24000, 24001, 24002, 24003, 24004, 24000, 24001, 24002, 24003, 24004, 24000, 24001, 24002, 24003, 24004])
    login_list = manager.list([
        {"name": "johnpeter", "un": getenv("USERNAME1"), "pw": getenv("PASSWORD1")},
        {"name": "johnpeter", "un": getenv("USERNAME1"), "pw": getenv("PASSWORD1")},
        {"name": "johnpeter", "un": getenv("USERNAME1"), "pw": getenv("PASSWORD1")},
        {"name": "peterjohn", "un": getenv("USERNAME2"), "pw": getenv("PASSWORD2")},
        {"name": "peterjohn", "un": getenv("USERNAME2"), "pw": getenv("PASSWORD2")},
        {"name": "peterjohn", "un": getenv("USERNAME2"), "pw": getenv("PASSWORD2")},
    ])
    return shared_ip_list, login_list


if __name__ == "__main__":
    num_processes = int(getenv("NUM_PROCESSES", 6))
    num_total_processes = int(getenv("NUM_PROCESSES", 1))

    with open("data/results", "w") as results_file:
        # Start the data at the last known chunk, so if something fails, only a little  progress is lost
        # Setup some logging things
        log_queue = Queue(-1)
        log_listener = Process(target=listener_process, args=(log_queue, listener_configurer))
        log_listener.start()

        # Loop through, one chunk at a time
        for i in range(num_total_processes):
            # Setup the list of ports and login information
            shared_ip_list, login_list = setup_logins_ports()
            with Pool(num_processes, initializer=Worker.initializer,
                      initargs=(login_list, shared_ip_list, log_queue, worker_configurer)) as p:
                result = p.apply(Worker.start)
                for i in range(num_processes):
                    p.apply(Worker.before_exit)
            results_file.flush()
            results_file.write(f"{json.dumps(result)} \n")
            results_file.flush()
