#!/usr/bin/env python

# Quadrant -- An exceedingly simplistic console App.net client.
# Copyright (C) 2012  Nicholas Knight
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import atexit
import ctypes
import os
import sys

from .commander import Commander
from select import select

PROMPT = ">>> "
timeout = 1

# Main
def interactive(adn, t):
    cmdr = Commander(adn=adn, interactive=True, t=t)
    
    def process_input(line):
        print ("Processing input: " + line)
        if not line:
            print_prompt()
            return
        line.rstrip()
        
        rl.add_history(line)
        
        if line[0] != '/':
            print ('{t.bold}Maybe you meant "/post"?{t.normal}'.format(t=t))
            print_prompt()
            return
        
        cmdr.execute_line(line[1:])
        
        print_prompt()
    
    ####
    # Setup readline
    # 
    # Python's included 'readline' module is, to put it mildly, limited.
    # As it turns out, things work just fine accessing libreadline through ctypes,
    # except, for unknown reasons, on OS X/Darwin, where things seem to be very
    # crashy.
    #
    # Thanks to James Pic for his non-blocking readline proof of concept at
    # https://gist.github.com/1252105

    rl = None
    _found_rl = False
    for so in ('libreadline.so', 'libreadline.so.6', 'libreadline.so.5',
        'libedit.so', 'libreadline.dylib', 'libedit.dylib'):
    
        try:
            rl = ctypes.cdll.LoadLibrary(so)
            _found_rl = True
        except OSError:
            continue
        break
    
    if not rl:
        raise Exception("Couldn't find libreadline")

    rlcallbackfunctype = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p)
    cbf = rlcallbackfunctype(process_input) # Or else it gets garbage collected and everything crashes...
    def print_prompt():
        rl.rl_callback_handler_remove()
        rl.rl_callback_handler_install(PROMPT, cbf)
        #rl.rl_parse_and_bind('set editing-mode vi')

    atexit.register(rl.rl_callback_handler_remove)

    ####
    
    
    print_prompt()
    
    while True:
        rlist, _, _ = select([sys.stdin], [], [], timeout)
        if rlist:
            rl.rl_callback_read_char()
