/*
 * Before working with any queues, it is necessary to connect
 * to the queue manager.
 *
 * Returns:
 * * true : On Success
 * * false: On Failure
 *
 *   comp_code and reason_code are also updated.
 *   reason will return a text description of the reason_code
 *
 * Throws:
 * * WMQ::WMQException if comp_code != MQCC_OK
 * * Except if :exception_on_error => false was supplied as a parameter
 *   to QueueManager.new
 */
VALUE QueueManager_connect(VALUE self)
{
    VALUE    name;
    VALUE    str;
    VALUE    val;
    VALUE    hash;

    PQUEUE_MANAGER pqm;
    Data_Get_Struct(self, QUEUE_MANAGER, pqm);
    pqm->already_connected = 0;

    Queue_manager_mq_load(pqm);                       /* Load MQ Library */

    name = rb_iv_get(self,"@name");
    name = StringValue(name);

    if(pqm->trace_level)
        printf("WMQ::QueueManager#connect() Connect to Queue Manager:%s\n", RSTRING(name)->ptr);

    if (pqm->hcon)                                    /* Disconnect from qmgr if already connected, ignore errors */
    {
        if(pqm->trace_level)
            printf("WMQ::QueueManager#connect() Already connected to Queue Manager:%s, Disconnecting first!\n", RSTRING(name)->ptr);

        pqm->MQDISC(&pqm->hcon, &pqm->comp_code, &pqm->reason_code);
    }

    pqm->MQCONNX(
            RSTRING(name)->ptr,      /* queue manager                  */
            &pqm->connect_options,   /* Connection Options             */
            &pqm->hcon,              /* connection handle              */
            &pqm->comp_code,         /* completion code                */
            &pqm->reason_code);      /* connect reason code            */

    if(pqm->trace_level)
        printf("WMQ::QueueManager#connect() MQCONNX completed with reason:%s, Handle:%d\n",
               wmq_reason(pqm->reason_code),
               pqm->hcon);

    if (pqm->comp_code == MQCC_FAILED)
    {
        pqm->hcon = 0;

        if (pqm->exception_on_error)
        {
            rb_raise(wmq_exception,
                     "WMQ::QueueManager#connect(). Error connecting to Queue Manager:%s, reason:%s",
                     RSTRING(name)->ptr,
                     wmq_reason(pqm->reason_code));
        }

        return Qfalse;
    }

    if (pqm->reason_code == MQRC_ALREADY_CONNECTED)
    {
        if(pqm->trace_level) printf("WMQ::QueueManager#connect() Already connected\n");
        pqm->already_connected = 1;
    }

    return Qtrue;
}