import logging
import os
import shlex
import subprocess
import time

def follow_file(path):
    while True:
        try:
            fd = os.open(path, os.O_RDONLY)
            current_ino = os.fstat(fd).st_ino
            with os.fdopen(fd, "r") as f:
                logging.info("Re-attached to file.")
                for line in f: pass
                while True:
                    line = f.readline()
                    if not line:
                        if os.stat(path).st_ino != current_ino or \
                           os.stat(path).st_size < f.tell():
                            break
                        else:
                            time.sleep(1.0)
                            yield None
                    else:
                        yield line.rstrip("\n")
        except FileNotFoundError:
            time.sleep(1.0)
            yield None

def feed_handler(cmd, data):
    try:
        handler = subprocess.Popen(shlex.split(cmd),
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   encoding='UTF-8')
        out_data, err_data = handler.communicate("%s\n" % data)
        if handler.returncode != 0:
            logging.warning("Handler exited with non-zero return code %d! (%s)" %
                            (handler.returncode, err_data))
    except Exception as e:
        logging.error("Error feeding handler: %s" % str(e))

def create_msg(title, icon, logfile, lines):
    msg = "<b>%s</b> %s" % (title, icon)
    msg += "<br>Too many errors in <i>%s</i>!" % logfile
    msg += "<br><pre>"
    for line in lines: msg += line + "\n"
    msg += "</pre>"
    return msg

def print_list(lst, ptr):
    txt = '['
    for i in range(0, len(lst)):
        txt += str( lst[(ptr + i) % len(lst)] )
        if i < len(lst) - 1: txt += ', '
    txt += ']'
    return txt
