#!/usr/bin/gjs

const Lang = imports.lang;
const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const GObject = imports.gi.GObject;
const GIRepository = imports.gi.GIRepository;
const System = imports.system;

const SEPARATOR = '='
const FLAG_USE_SSL = 4
const FLAG_AUTO_CONNECT = 8

function flagMatches(flag, bitmask) {
    if (flag == NaN)
        return false;
    return (flag & bitmask);
}

function parseSection(section) {
    // Split into lines, and stuff into a dict
    let keys = {}
    let lines = section.split('\n');
    let array;
    for (let i = 0; i < lines.length; i++) {
        if (lines[i][1] != '=') {
            log('Ignoring ' + lines[i]);
            continue;
        }
        let key = lines[i][0];
        // Ignore keys that have already been set
        if (keys[key])
            continue;
        let value = lines[i].substring(2);
        keys[key] = value;
    }

    // Ignore if there's no server line
    if (!keys['S'])
        return null;

    let name = keys['N'];
    if (!name)
        name = keys['S'];

    // Ignore if the server isn't autoconnect
    if (!flagMatches(Number(keys['F']), FLAG_AUTO_CONNECT)) {
        //log('Server ' + name + ' is not autoconnect, ignoring');
        return null;
    }

    let server = {};
    server.networkName = name;
    //FIXME parse 'S'?
    server.serverAddress = keys['S'];
    server.secureConnection = flagMatches(Number(keys['F']), FLAG_USE_SSL);
    server.nickname = keys['I'];
    server.realName = keys['R'];
    server.rooms = keys['J'];
    server.nickservPassword = keys['B'];
    server.serverPassword = keys['P'];

    print ('Parsed ' + name);

    return server;
}

function parseConfiguration(data) {
    // Split into sections and parse each one
    let sections = String(data).split('\n\n');
    let servers = [];
    for (let i = 0; i < sections.length; i++) {
        let server = parseSection(sections[i]);
        if (server)
            servers.push(server);
    }

    print ('Parsed ' + servers.length + ' servers');

    //FIXME add each server to Polari if they don't already exist
}

// Open the xchat-gnome config
let path = GLib.get_home_dir() + '/.xchat-gnome/servlist_.conf';
if (ARGV.length == 1)
    path = ARGV[0];
let file = Gio.File.new_for_path(path);

let success, data;
try {
    [success, data, ] = file.load_contents(null);
    parseConfiguration(data);
} catch(e) {
    log('Failed to load configuration file: ' + e.message);
}
