/*
 *  oper.cpp
 *  (C) gsd 2001
 */                                                                             

#include <algorithm>
// #include <sstream>      // for standard
#include <strstream>       // for g++

#include "oper.h"

using namespace std;

COperMaint::COperMaint( std::istream& is, std::ostream& os)
            : m_input_source( is ), m_output_source( os )
{
    init();

    m_scid = 0;
    m_dbid = 0;
    m_is_exit = false;

    m_sid = getsid();
}

void COperMaint::init()
{
    m_commands["REG"]   = 1;    //  Register new user
    m_commands["UNREG"] = 2;    //  Unregister user
    m_commands["CALL"]  = 3;    //  Initiate a call
    m_commands["DISC"]  = 4;    //  Clear a call
    m_commands["LACT"]  = 5;    //  List active calls
    m_commands["LREG"]  = 6;    //  List registered users
    m_commands["EXIT"]  = 7;    //  Exit 
}

void COperMaint::doit()
{
    string  current_line;

    while ( ! m_is_exit  &&  getline( m_input_source, current_line) )
    {
        if ( parse( current_line) )
            execute();
    }
}

bool COperMaint::parse( string line)
{

//    istringstream is( line);
    istrstream  is( line.c_str());
    string      command;

    if ( is >> command )
    {
//        line.erase(0, command.size());
        m_arguments = line;

        if ( (m_it_current = m_commands.find(command)) == m_commands.end() )
        {
            cerr << command << ": command not found" << endl;
            return false;
        }
//      return m_it_current != m_commands.end(); 
        return true;
    }
    else 
        return false;
}

void COperMaint::execute()
{
    switch( m_it_current->second )
    {
    default: cerr<<"execute error"<< endl; uexit(); break;
    case  1: send( m_dbid, m_arguments);  break;
    case  2: send( m_dbid, m_arguments);  break;
    case  3: send( m_scid, m_arguments);  break;
    case  4: send( m_scid, m_arguments);  break;
    case  5: send( m_scid, m_arguments);  break;
    case  6: send( m_dbid, m_arguments);  break;
    case  7: uexit();                               break;
    }
}

void COperMaint::assign( long scid, long dbid)
{
    m_scid = scid;
    m_dbid = dbid;
}

void COperMaint::receive( long sender, string message)
{
    m_output_source << "OperMaint output from " 
                    << sender << ", message: "
                    << message << endl;
}

void COperMaint::uexit()
{
    m_is_exit = true;
    cout << "Exiting on user request" << endl;
}