#!/usr/bin/python

import sys
import curses
import os
import time


class Cursor:
    pass

class Term:
    pass


def ls(term):
    #output = os.popen("ssh -p 2222 vagrant@localhost 'ls %s*'" % term).read()

    output = os.popen('ls %s*' % term).read()

    return output.split()

def update(term, prev, c):
    if c == curses.KEY_BACKSPACE or c == 127:
        return term[:-1], term
    elif c >= 0 and c < 255:
        return term + chr(c), term
    else:
        return term, term

def update_screen(stdscr, term, prev, c):
    if len(term) < len(prev):
        stdscr.addstr(0, len(term), " ")

    if term != prev:
        stdscr.addstr(20, 0, "(%d)" % c)
        stdscr.addstr(0, 0, term)
        stdscr.refresh()


def test_update_interval(interval):
    """>>> i = UpdateInterval(current=0.2, previous=0.1)
>>> i.has_millis_between(50)
True
>>> i.has_millis_between(200)
False"""
    pass


def update_interval(interval):
    return TimestampInterval(current=time.time(), previous=interval.previous)

class TimestampInterval:

    def __init__(self, current=None, previous=None):
        self.current = current
        self.previous = previous

    def has_millis_between(self, millis):
        return (self.current - self.previous) * 1000 > millis



def update_state(state, c):
    if c != -1:


class SearchState:

    def __init__(self, current_term, previous_term, current_time, previous_time, 
            current_output, previous_output):
        self.current_term = current_term
        self.previous_term = previous_term
        self.current_time = current_time
        self.previous_time = previous_time
        self.current_output = current_output
        self.previous_output = previous_output




def main_loop(stdscr, *args):

    log = open('lv.log', 'w')
    state = SearchState("", "", time.time(), time.time(), [], [])
    term, prev = "", ""
    interval = TimestampInterval(current=time.time(), previous=time.time())

    stdscr.nodelay(True)

    while 1:
        c = stdscr.getch()
        state = update_state(state, c)

        if c != -1:
            term, prev = update(term, prev, c)

        interval = update_interval(interval)
        log.write('current %2.2f prev %2.2f\n' %  (interval.current, interval.previous))
        log.flush()
  
        if interval.has_millis_between(300) and len(term) > 0:
           for idx, val in enumerate(ls(term)):
                stdscr.addstr(1, 0, "output (at %s):" % time.time())
                stdscr.addstr(idx + 2, 0, val)
                stdscr.refresh()
        
        update_screen(stdscr, term, prev, c)
        time.sleep(0.1)

def main(args):
    print args

    if len(args) > 0 and args[0] == "test":
        import doctest
        doctest.testmod()
    else:
        curses.wrapper(main_loop)
    print 'done'

if __name__ == '__main__':
    main(sys.argv[1:])

