"""
Copyright CNRS (https://www.cnrs.fr/index.php/en)
Contributor(s): Eric Debreuve (eric.debreuve@cnrs.fr) since 2025
SEE COPYRIGHT NOTICE BELOW
"""

import dataclasses as d
from multiprocessing import Queue as NewQueue
from multiprocessing import current_process as CurrentProcess
from queue import Empty as EmptyError
from threading import Thread as thread_t

from mpss_tools_36.constant.generic import REQUEST_STOP
from mpss_tools_36.constant.process import MAIN_PROCESS_NAME
from mpss_tools_36.extension.data_class import NO_CHOICE
from mpss_tools_36.type.line import line_end_t, line_t


@d.dataclass(slots=True, repr=False, eq=False)
class server_t:
    name: str

    _lines: list[line_t] = NO_CHOICE(list)
    _thread: thread_t | None = NO_CHOICE(None)

    def NewLine(self) -> tuple[line_end_t, line_end_t]:
        """"""
        assert self._thread is None

        request_line_end, answer_line_end = NewQueue(), NewQueue()
        self._lines.append(line_t(request=request_line_end, answer=answer_line_end))

        return request_line_end, answer_line_end

    def Start(self) -> None:
        """"""
        assert CurrentProcess().name == MAIN_PROCESS_NAME
        assert self._thread is None
        assert self._lines.__len__() > 0

        self._thread = thread_t(target=self._Run)
        self._thread.start()

    def _Run(self) -> None:
        """"""
        raise NotImplementedError

    @staticmethod
    def ActiveRequests(
        active_lines: list[line_t], /
    ) -> list[tuple[line_end_t, line_end_t, str | tuple]]:
        """"""
        output = []

        for line in tuple(active_lines):
            request_line_end = line.request
            try:
                request = request_line_end.get(False)
            except EmptyError:
                pass
            else:
                output.append((request_line_end, line.answer, request))

        return output

    def Stop(self, *_, **__) -> None:
        """"""
        assert CurrentProcess().name == MAIN_PROCESS_NAME
        assert self._thread is not None

        # There are necessarily lines (see Start).
        self._lines[0].request.put(REQUEST_STOP)
        self._thread.join()
        self._thread = None

        for line_ends in self._lines:
            for line_end in line_ends:
                line_end.close()
                line_end.join_thread()
        self._lines.clear()


"""
COPYRIGHT NOTICE

This software is governed by the CeCILL  license under French law and
abiding by the rules of distribution of free software.  You can  use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability.

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and,  more generally, to use and operate it in the
same conditions as regards security.

The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.

SEE LICENCE NOTICE: file README-LICENCE-utf8.txt at project source root.
"""
