import os

from celilo import test_suite
from celilo.main import escape_string, format_channels, format_as_uri


def file_exists(atak_kill_script):
    if not os.path.exists(atak_kill_script):
        raise FileNotFoundError(f"File {atak_kill_script} does not exist")
    pass


def printError(text):
    print(f"\033[91m{text}\033[0m")


class Adb:

    def __init__(self, package):
        self.package = package
        pass

    def send_adb_command(self, command):
        os.system(command)

    # def send_broadcast(self, test):
    #     broadcast_id = test_suite.generate_UUID()
    #     command = f"adb -s {test.sender} shell am broadcast -a {test.action} " \
    #               f"--es message_body \'{escape_string(test.extras)} {format_as_uri(broadcast_id)}\ ' " \
    #               f"--es channels '{format_channels(test.channels)}'"
    #
    #     # print("sending broadcast: " + command)
    #     self.send_adb_command(command)
    #     return broadcast_id

    def adb_logcat(self, device):
        command = f"adb -s {device} logcat"
        self.send_adb_command(command)

    def devices(self):
        command = "adb devices | tail -n +2 | cut -sf 1"
        devices = os.popen(command).read().strip()
        devices = devices.split("\n")
        return devices

    def start_app(self, package, devices, workspace_id, config, workspace_key, workspace_name):
        if package == "com.atakmap.app.civ":
            self.start_atak(devices, workspace_id, config, workspace_key, workspace_name)
        else:
            self.start_test_app(devices, workspace_id, config, workspace_key, workspace_name)


    def start_atak(self, devices, workspace_id, config, workspace_key, workspace_name):
        print("Testing ATAK")
        atak_kill_script = "../cli/atak_kill.sh"
        file_exists(atak_kill_script)
        os.system(f"sh {atak_kill_script}")
        for device in devices:
            command = self.get_command(self.is_atak(), device, config, workspace_id, workspace_key, workspace_name)
            print(f"Running: {command}")
            os.system(command)

    def get_command(self, isAtak, device, config, workspace_id, workspace_key, workspace_name):
        if isAtak:
            host = "somewear"
        else:
            host = "atak_somewear_test"

        if device in config:
            msgInterval = config[device]["message_interval"]
            callsign = config[device].get("callsign", "")
            callsignParam = f"callsign={callsign}" if callsign else ""
        else:
            msgInterval = 0
            callsignParam = ""
            printError(f"Device {device} not found in config file; please configure")

        # workspace key overrides workspace_id; if a workspace key is provided, then we will format the uri
        # to join the workspace
        print("Workspace Key for command: ", workspace_key)
        if workspace_key:
            command = (
                f"adb -s {device} shell am start -a android.intent.action.VIEW -d "
                f"\"{host}://api.somewear.co:443/workspace-key?key={workspace_key}\&name={workspace_name}\&msgInterval={msgInterval}\&{callsignParam}\""
            )
        else:
            command = (
                f"adb -s {device} shell am start -a android.intent.action.VIEW -d "
                f"\"{host}://workspace/{workspace_id}?msgInterval={msgInterval}\&{callsignParam}\""
            )
        return command

    def start_test_app(self, devices, workspace_id, config, workspace_key, workspace_name):
        print("Testing ATAK")
        atak_kill_script = "../cli/atak_test_kill.sh"
        file_exists(atak_kill_script)
        os.system(f"sh {atak_kill_script}")
        os.system(f"devices starting: {devices}")
        for device in devices:
            command = self.get_command(False, device, config, workspace_id, workspace_key, workspace_name)
            print(f"Running: {command}")
            os.system(command)

    def is_atak(self):
        return self.package == "com.atakmap.app.civ"

