import socket
import telnetlib

from lib_python import logger

__INDEX_NOT_FOUND = -1
__RESPONSE_OK = "OK\r\n"


def open_android_console(host="localhost", port=5554):
    client = None

    try:
        client = telnetlib.Telnet(host, port)
    except socket.error as er:
        logger.error("Unable to open the socket to {0}:{1}, original error: {2}".format(host, port, repr(er)))

    return client


def enable_roaming_on_emulator(console, timeout=15):
    """
    Sets emulator's connection as roaming.

    :param console: Android console instance
    :param timeout: operation timeout in seconds
    :returns: True, provided that network setting has been successfully changed, False otherwise
    """
    return __issue_console_command(console, "gsm data roaming")


def disable_data_connection_on_emulator(console, timeout=15):
    """
    Sets emulator's connection as roaming.

    :param console: Android console instance
    :param timeout: operation timeout in seconds
    :returns: True, provided that network setting has been successfully changed, False otherwise
    """

    # read_everything
    return __issue_console_command(console, "gsm data off", timeout)


def __issue_console_command(console, message, timeout):
    # read_everything
    response = ""

    line = console.read_very_eager()
    while len(line) > 0:
        response += line
        line = console.read_very_eager()

    logger.debug(response)

    # change network settings
    console.write(message + '\n')
    logger.debug(message)

    logger.debug(response)

    try:
        response = console.read_until(__RESPONSE_OK, timeout)
    except EOFError:
        logger.error("Telnet server did not respond with OK: {0}".format(response))
        return False

    if not response.endswith(__RESPONSE_OK):
        logger.error("Telnet server did not respond with OK: {0}".format(response))
        return False

    return True
