import logging
import os
import subprocess
import tempfile
from datetime import datetime
from subprocess import call

import errno

EDITOR = os.environ.get('EDITOR', 'vim')

FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('tcpserver')

logger.setLevel(logging.DEBUG)


def parse_note_from_vim():
    with tempfile.NamedTemporaryFile(suffix='task') as temp:
        subprocess.call([EDITOR, temp.name])
        return open(temp.name, 'r').read()


def string_input(prompt_text):
    return input(prompt_text)


def int_input(prompt_text):
    return input(prompt_text)


def get_default_title():
    today = datetime.date.today()
    return str(today)


def query(key, line):
    if key is None:
        key = ""
    key_words = key.split(" ")

    found = True
    for key in key_words:
        found = found and key in line

    return found


def open_in_editor(initial_message=""):
    with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
        if type(initial_message) == str:
            initial_message = str.encode(initial_message)

        tf.write(initial_message)
        tf.flush()
        call([EDITOR, tf.name])

        tf.seek(0)
        return tf.read()


def create_directories_of_file(filename):
    if not os.path.exists(os.path.dirname(filename)):
        try:
            os.makedirs(os.path.dirname(filename))
        except OSError as exc:  # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise


def list_files(path):
    for root, dirs, files in os.walk(path):
        if '.git' in dirs:
            dirs.remove('.git')
        level = root.replace(path, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

import logging
import os
import subprocess
import tempfile
from datetime import datetime
from subprocess import call

import errno

EDITOR = os.environ.get('EDITOR', 'vim')

FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('tcpserver')

logger.setLevel(logging.DEBUG)


def parse_note_from_vim():
    with tempfile.NamedTemporaryFile(suffix='task') as temp:
        subprocess.call([EDITOR, temp.name])
        return open(temp.name, 'r').read()


def string_input(prompt_text):
    return input(prompt_text)


def int_input(prompt_text):
    return input(prompt_text)


def get_default_title():
    today = datetime.date.today()
    return str(today)


def query(key, line):
    if key is None:
        key = ""
    key_words = key.split(" ")

    found = True
    for key in key_words:
        found = found and key in line

    return found


def open_in_editor(initial_message=""):
    with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
        if type(initial_message) == str:
            initial_message = str.encode(initial_message)

        tf.write(initial_message)
        tf.flush()
        call([EDITOR, tf.name])

        tf.seek(0)
        return tf.read()


def create_directories_of_file(filename):
    if not os.path.exists(os.path.dirname(filename)):
        try:
            os.makedirs(os.path.dirname(filename))
        except OSError as exc:  # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise


def list_files(path):
    for root, dirs, files in os.walk(path):
        if '.git' in dirs:
            dirs.remove('.git')
        level = root.replace(path, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

# Guard against race condition