#   Copyright (C) 2025 Stephen Fairchild (s-fairchild@users.sourceforge.net)
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program in the file entitled COPYING.
#   If not, see <http://www.gnu.org/licenses/>.

__all__ = ["main"]

_description_ = "Launch back-end and make/break JACK port connections."


import os
import time
import random
import logging
import tempfile
from datetime import datetime
from uuid import uuid4 as uuid

from .common import mk_ping, Backend, prepend, mk_jack_ports_list

logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger("testing")


def main():
    print(_description_)

    logger.setLevel(logging.INFO)
    os.environ["has_head"] = "0"
    os.environ["extant_port_check"] = "0"
    with tempfile.TemporaryDirectory() as tmpdirname:
        with Backend(0, tmpdirname) as (mx_send, _, receive):
            ports_list = mk_jack_ports_list(mx_send, receive)

            hw = ports_list("hwoutputs"), ports_list("hwinputs")
            both = ports_list("outputs"), ports_list("inputs")
            sw = [list(set(b) - set(h)) for b, h in zip(both, hw)]

            print("Audio feedback noise warning!")
            print("Before doing this test physically turn down your audio or disconnect headphones/speakers.")
            print("User assumes responsibility for any hardware or hearing damage resulting from this test.")

            choice = input("Choose port class hardware/software/both: enter (h, s, b) ")
            choice = choice.strip()
            ports = {"h": hw, "s": sw, "b": both}.get(choice)

            if input("Add fake ports? (y/n) ").strip().lower().startswith("y"):
                for port in ports:
                    for _ in range(2):
                        port.append(f"{str(uuid())}:{str(uuid())}")

            legal_shit = input("Have you taken steps to protect your hearing? Enter Yes/No: ")
            if legal_shit != "Yes":
                print("guess not: exiting")
                exit(0)

            def wire(operation, source, sink):
                mx_send(f"ACTN=jack{operation}\nJPRT={source}\nJPT2={sink}\n")

            start_time = datetime.now()

            while 1:
                repeat = 10
                while repeat:
                    wire(random.choice(["connect", "disconnect"]),
                         random.choice(ports[0]), random.choice(ports[1]))
                    repeat -= 1

                time.sleep(1)
                logger.info(_description_)
                logger.info(f"Subtest '{choice}', Uptime: {datetime.now() - start_time}")
