/* main.c
*/

#include <stdio.h>
#include <stdlib.h>
#include "bot/context.h"
#include "grammar/types.h"

int main(int argc, char **argv)
{
    GString *filename;
    struct BotUserInfo user;
    struct BotXmppCtx bctx;
    int startup_code;

    /* take a jid and password on the command line */
    if (argc != 4) {
        fprintf(stderr, "Usage: bot <jid> <pass> <csv_file>\n\n");
        return 1;
    }

    if (!g_utf8_validate(argv[1], -1, NULL)
        || !g_utf8_validate(argv[2], -1, NULL)
        || !g_utf8_validate(argv[3], -1, NULL)) {
        fprintf(stderr, "<jid>, <pass> and <csv_file> should be valid UTF-8 strings.\n\n");
        return 1;
    }
    
    user.jid = g_string_new(argv[1]);
    user.pass = g_string_new(argv[2]);
    filename = g_string_new(argv[3]);

    bot_set_filename(filename);

    /* perform the startup and connect routine */
    startup_code = bot_xmpp_startup(user, &bctx);
    if(startup_code != 0) {
        /* something went wrong at startup */
        return startup_code;
    }

    /* enter the event loop - 
       our connect handler will trigger an exit */
    xmpp_run(bctx.ctx);

    /* release our connection and context */
    /* final shutdown of the library */
    bot_xmpp_shutdown(&bctx);

    /* Free user data, leave underlying strings as they are part of argv*/
    bot_free_user_data(user, filename, false);

    return 0;
}
