#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include <completion.hh>

namespace py = pybind11;

completion::string_list
py_completion( const std::string& db_path, const std::string& key )
{
    auto db = completion::load_database( db_path );
    return completion::search( db.channels.begin( ), db.channels.end( ), key );
}

completion::string_list
py_completion_iterator( py::iterator it, const std::string& key )
{
    completion::Database db;

    while ( it != it.end( ) )
    {
        std::string s = ( *it ).cast< std::string >( );
        if ( !s.empty( ) && s.back( ) == '\n' )
        {
            s.pop_back( );
        }
        if ( !s.empty( ) )
        {
            auto space = s.find( ' ' );
            if ( space < std::string::npos )
            {
                s.resize( space );
            }
            db.channels.emplace_back( std::move( s ) );
        }
        ++it;
    }
    completion::sort( db );
    return completion::search( db.channels.begin( ), db.channels.end( ), key );
}

PYBIND11_PLUGIN( ligo_channels )
{
    py::module m( "ligo_channels", "LIGO channel name completion" );

    m.def( "completion",
           &py_completion,
           "Given a filename return the next possible "
           "completions for the given key" );
    m.def( "completion_iterator",
           &py_completion_iterator,
           "Given an iterator of "
           "channel names, return the "
           "next possibly completions "
           "for the given key" );

    return m.ptr( );
}