#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
from itertools import cycle
from multiprocessing import Queue

from .settings import logger
from .workers.logbroker_receiver import LogBrokerReceiver
from .workers.search_data_extractor import SearchDataExtractor
from .workers.unistat import Unistat


def main():
    search_data_extractor_queue = Queue()
    unistat_queue = Queue()

    service_process_factory = [
        lambda: LogBrokerReceiver(search_data_extractor_queue=search_data_extractor_queue,
                                  unistat_queue=unistat_queue),
        lambda: SearchDataExtractor(search_data_extractor_queue=search_data_extractor_queue,
                                    unistat_queue=unistat_queue),
        lambda: Unistat(unistat_queue=unistat_queue)
    ]

    pool = [None] * len(service_process_factory)
    for p_index, factory in cycle(enumerate(service_process_factory)):
        if pool[p_index] is None or not pool[p_index].is_alive():
            pool[p_index] = factory()
            logger.info(f'Process "{pool[p_index].__class__.__name__}" is starting...')
            pool[p_index].start()
        time.sleep(0.1)


if __name__ == '__main__':
    main()
