#include "config.h"

static void config_default(config_t *cfg) {
    cfg->count = 0;
    bookmark_t a = {"Bottomless MRC", "mrc.bottomlessabyss.net", 7000, "StingRay", "#lobby", 1};
    bookmark_t b = {"Libera", "irc.libera.chat", 6667, "StingRay", "##chat", 0};
    config_add_or_update(cfg, &a);
    config_add_or_update(cfg, &b);
}

void config_init(config_t *cfg) {
    memset(cfg, 0, sizeof(*cfg));
#ifdef _WIN32
    const char *home = getenv("USERPROFILE");
    if (!home) home = ".";
    snprintf(cfg->path, sizeof(cfg->path), "%s\\anet_irc_bookmarks.txt", home);
#else
    const char *home = getenv("HOME");
    if (!home) home = ".";
    snprintf(cfg->path, sizeof(cfg->path), "%s/.anet_irc_bookmarks", home);
#endif
}

void config_load(config_t *cfg) {
    FILE *fp = fopen(cfg->path, "r");
    cfg->count = 0;
    if (!fp) {
        config_default(cfg);
        config_save(cfg);
        return;
    }
    char line[512];
    while (fgets(line, sizeof(line), fp)) {
        trim(line);
        if (!line[0]) continue;
        bookmark_t bm;
        memset(&bm, 0, sizeof(bm));
        char *p = strtok(line, "|"); if (!p) continue; safe_strcpy(bm.label, p, sizeof(bm.label));
        p = strtok(NULL, "|"); if (!p) continue; safe_strcpy(bm.server, p, sizeof(bm.server));
        p = strtok(NULL, "|"); if (!p) continue; bm.port = atoi(p);
        p = strtok(NULL, "|"); if (!p) continue; safe_strcpy(bm.nick, p, sizeof(bm.nick));
        p = strtok(NULL, "|"); if (!p) continue; safe_strcpy(bm.channel, p, sizeof(bm.channel));
        p = strtok(NULL, "|"); if (!p) continue; bm.tls = atoi(p);
        p = strtok(NULL, "|"); if (p) safe_strcpy(bm.password, p, sizeof(bm.password));
        config_add_or_update(cfg, &bm);
    }
    fclose(fp);
    if (cfg->count == 0) config_default(cfg);
}

void config_save(config_t *cfg) {
    FILE *fp = fopen(cfg->path, "w");
    if (!fp) return;
    for (int i = 0; i < cfg->count; i++) {
        bookmark_t *b = &cfg->items[i];
        fprintf(fp, "%s|%s|%d|%s|%s|%d|%s\n", b->label, b->server, b->port, b->nick, b->channel, b->tls, b->password);
    }
    fclose(fp);
}

void config_add_or_update(config_t *cfg, const bookmark_t *bm) {
    if (!cfg || !bm || !bm->label[0]) return;
    for (int i = 0; i < cfg->count; i++) {
        if (strcasecmp(cfg->items[i].label, bm->label) == 0) {
            cfg->items[i] = *bm;
            return;
        }
    }
    if (cfg->count < CFG_MAX_BOOKMARKS) {
        cfg->items[cfg->count++] = *bm;
    }
}

void config_delete(config_t *cfg, int idx) {
    if (!cfg || idx < 0 || idx >= cfg->count) return;
    for (int i = idx; i < cfg->count - 1; i++) cfg->items[i] = cfg->items[i + 1];
    cfg->count--;
}
