#include <config.h>
#include <stdio.h>
#include "IMSvr.hh"
#include "IMSvrCfg.hh"
#include "IMConnection.hh"
#include "LEMgr.hh"
#include "IIIMProtocol.hh"
#include "IMScheduler.hh"

bool
IMSvr::config_lepath(
    const char *lepath
)
{
    LEMgr *plm = new LEMgr(lepath);
    if (!plm) return false;
    if (plemgr) delete plemgr;
    plemgr = plm;
    return true;
}

bool
IMSvr::config_le (
    const char *lepath,
    IMLEXMLConf &xml
)
{
    LEMgr *plm = new LEMgr (lepath, xml);

    if (!plm)
	return false;
    if (plemgr)
	delete plemgr;
    plemgr = plm;

    return true;
}

bool
IMSvr::config_listenaddress(
    IMSocketAddressVec& x_addrvec
)
{
    IIIMProtocol *pimp = new IIIMProtocol(this);
    if (!pimp) return false;

    addrvec = x_addrvec;

    pimp->set_server_listen_address(addrvec);
    if (pimprotocol)
	delete pimprotocol;
    pimprotocol = pimp;
    IMScheduler::get_instance()->set_improtocol(pimp);

    return true;
}

bool
IMSvr::config_conversionkeys(
    const char *keys
)
{
    IMKeyParser *pkp = new IMKeyParser(keys);

    if (!pkp)
        return false;
    if (pkeyparser)
        delete pkeyparser;

    pkeyparser = pkp;

    return true;
}

int
IMSvr::start()
{
    if (!pcfg->configure(this)) return IMSVR_CONFIG_ERROR;
    ASSERT(plemgr);
    ASSERT(pimprotocol);

    IMScheduler::get_instance()->start();

    return IMSVR_EXIT_SUCCESS;
}

void
IMSvr::reload()
{
    if (plemgr)
      plemgr->reload();
}

void
IMSvr::terminate()
{
    IMScheduler::get_instance()->stop();
    return;
}

bool
IMSvr::request_accept(
    int fd
)
{
    if (usermgr.fd_ok(fd)) return true;

    return false;
}

IMConnection*
IMSvr::create_imconnection(
    IMUser *puser,
    const string &hostname
)
{
    IMConnection* pc;

    pc = new IMConnection(this, puser, hostname);
    if (!pc) return NULL;
    imclist.push_back(pc);

    return pc;
}

bool
IMSvr::remove_imconnection(
    IMConnection *pc
)
{
    imclist.remove(pc);
    return true;
}

IMHandler*
IMSvr::request_connect(
    int fd,
    const u16string &username,
    const string &hostname,
    const u16string &password,
    const IMAuthList &authlist
)
{
    IMUser *puser;
    IMConnection *pimc;

    // TODO
    if (!username.get_charstr()) return NULL;
    puser = usermgr.create_imuser(fd, username.get_charstr(), password.get_charstr());
    if (!puser) return NULL;
    pimc = create_imconnection(puser, hostname);
    if (!pimc) return NULL;

    return pimc;
}

IMSvr::IMSvr(
    IMSvrCfg *p_cfg
) :
    pcfg(p_cfg)
{
    plemgr = NULL;
    pimprotocol = NULL;
    pkeyparser = NULL;
}

IMSvr::~IMSvr()
{
    if (plemgr) delete plemgr;
    destroy_all(imclist);
}

/* Local Variables: */
/* c-file-style: "iiim-project" */
/* End: */
