from __future__ import print_function, division, absolute_import

import os
import logging
import subprocess

from lxml import etree

from .compatibility import urlparse

format = ('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.basicConfig(format=format, level=logging.INFO)
logging.getLogger("requests").setLevel(logging.WARNING)


def set_logging(level):
    logger = logging.getLogger('knit')
    logger.setLevel(level)


def parse_xml(f, search_string=''):
    conf = {}
    url = conf_find(f, search_string)
    if url:
        u = urlparse(url)

        # handle host:port with no :// preabmle
        if u.path == url:
            conf['host'], conf['port'] = url.split(':')
        else:
            conf['host'] = u.hostname
            conf['port'] = u.port
    return conf


def conf_find(fp='', name=''):
    """
    Utility function to help parse hadoop configuration files.

    Parameters
    ----------
    fp : string
        file path
    name : string
        name to search

    Returns
    -------
    value : string

    Examples
    --------

    with the following xml
    <property>
      <name>fs.defaultFS</name>
      <value>hdfs://knit-host:9000</value>
    </property>

    >>> conf_find('fs.defaultFS')

    """
    tree = etree.parse(fp)
    elem = tree.xpath("./property[descendant::text()='{}']".format(name))
    try:
        hdfs_url = elem[0]
        return hdfs_url.find('value').text
    except IndexError:
        return ''


def shell_out(cmd=None):
    """
    Thin layer on check_output to return data as strings

    Parameters
    ----------
    cmd : list
        command to run

    Returns
    -------
    result : str
        result of shell command
    """
    return subprocess.check_output(cmd).decode('utf-8')
