import docker
import os
import getpass
import logging

_image = "dokoliho/botserver"
_uid = os.getuid()
_username = getpass.getuser()
_containername = "botserver_" + _username
_port = 62187 + _uid
_logger = logging.getLogger(__name__)
_from_env=False
_verbose=False

def _client():
    if _from_env:
        client = docker.from_env()
    else:
        client = docker.DockerClient(base_url='tcp://172.17.0.1:2375')
    return client

def _get_running_container():
    client = _client()
    try:
        return client.containers.get(_containername)
    except:
        msg = f"Container {_containername} not found."
        if _verbose: print(msg)
        _logger.info(msg)
    return None

def connect_remote_daemon(flag):
    global _from_env
    _from_env =  not flag

def stop_container():
    container = _get_running_container()
    if container is not None:
        container.stop()
        container.remove()
        msg = f"Container {_containername} stopped."
        if _verbose: print(msg)
        _logger.info(msg)

def start_container(verbose=False):
    global _verbose
    _verbose = verbose
    stop_container()
    client = _client()
    try:
        client.containers.run(_image,
                              command=["sleep", "inf"],
                              detach=True,
                              name=_containername,
                              ports={63187: _port})
        msg = f"Container {_containername} started with port {_port}"
        if _verbose: print(msg)
        _logger.info(msg)
        return _port
    except Exception as e:
        if _verbose: print(str(e))
        _logger.warning(str(e))
    return None

def exec_in_container(command):
    container = _get_running_container()
    if container == None:
        msg = f"Container {_containername} not running."
        _logger.warning(msg)
        raise Exception(msg)
    try:
        msg = f"Executing {command}"
        if _verbose: print(msg)
        _logger.info(msg)
        result = container.exec_run(command, stream=True)
    except Exception as e:
        print(str(e))
        _logger.warning(str(e))
        return
    for line in result.output:
        print(line.decode("utf-8"))
    msg = f"Execution of {command} finished."
    if _verbose: print(msg)
    _logger.info(msg)

def exec_synced_in_container(command):
    container = _get_running_container()
    if container == None:
        msg = f"Container {_containername} not running."
        _logger.warning(msg)
        raise Exception(msg)
    try:
        msg = f"Executing (sync) {command}"
        if _verbose: print(msg)
        _logger.info(msg)
        exit_code, output = container.exec_run(command)
    except Exception as e:
        print(str(e))
        return
    print(output.decode("utf-8") )
    msg = f"Execution of {command} finished."
    if _verbose: print(msg)
    _logger.info(msg)

def print_logs():
    container = _get_running_container()
    if container == None:
        msg = f"Container {_containername} not running."
        _logger.warning(msg)
        raise Exception(msg)
    print(container.logs().decode("utf-8"))


if __name__ == "__main__":
    connect_remote_daemon(False)
    start_container(verbose=True)
#    exec_in_container("echo 'hello world'")
    exec_in_container("/bots/server/bots training")
    stop_container()

