#!/usr/bin/env python
# -*- coding: utf-8 -*-

from xml.dom.minidom import Document
import mimetypes
import logging
import subprocess


def run_subprocess_and_wait(cmd, shell=True):
    """
        Run subprocess and wait for it to finish
        @cmd: command to run
        @return: process object
    """
    logging.info('Run cmd: {}'.format(cmd))
    if isinstance(cmd, str) and not shell:
        # если передана строка, разделяем её по пробелам
        cmd = cmd.split(' ')
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               shell=shell,
                               close_fds=True)
    process.wait()
    return process


class DictToXml(object):
    """
        Class from http://code.activestate.com/recipes/577739-dict2xml/
    """

    def __init__(self, structure):
        self.doc = Document()
        if len(structure) == 1:
            root_name = str(structure.keys()[0])
            self.root = self.doc.createElement(root_name)
            self.doc.appendChild(self.root)
            self.build(self.root, structure[root_name])

    def build(self, father, structure):
        if type(structure) == dict:
            for k in structure:
                tag = self.doc.createElement(k)
                father.appendChild(tag)
                self.build(tag, structure[k])

        elif type(structure) == list:
            grandFather = father.parentNode
            tagName = father.tagName
            grandFather.removeChild(father)
            for l in structure:
                tag = self.doc.createElement(tagName)
                self.build(tag, l)
                grandFather.appendChild(tag)

        else:
            # договорились в выдаваемом xml заменять None на пустую строку
            if structure is None:
                data = ''
            else:
                data = str(structure)
            tag = self.doc.createTextNode(data)
            father.appendChild(tag)

    def display(self):
        return self.doc.toprettyxml(indent="  ")


class DirectOutput(Exception):
    def __init__(self, filename):
        super(DirectOutput, self).__init__()
        self.file = filename
        self.mimetype = mimetypes.guess_type(filename)[
            0] or 'application/octet-stream'

    def __format__(self, *args, **kwargs):
        return self.get_content()

    def get_content(self):
        fh = open(self.file, 'rb')
        res = fh.read()
        fh.close()
        return res


class NotFoundError(Exception):
    """
        Exception for errors in requested url
        May be caused by:
         - malformed URL
         - non-existing test id
    """
    pass
