/*
    list - Imports list of stations
    Copyright (C) 2010-2015 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include "header.h"

#include "bfu.h"
#include "fifo.h"
#include "net.h"
#include "qsodb.h"
#include "session.h"
#include "stats.h"

#define LIST_DELIM "\t "

void import_list(void *xxx, char *filename){
    FILE *f;
    GString *gs;
    char *token_ptr;
    int i;
    int l = 0;
    
    f = fopen(filename, "r");
    if (!f) {
        log_addf(VTEXT(T_CANT_READ_S), filename);
        return;
    }
    
    gs = g_string_sized_new(120);

    while(zfile_fgets(gs, f, 0)!=NULL ){
        struct qso *q;
        char *c, *w, *r;
        l++;

        c = strtok_r(gs->str, LIST_DELIM, &token_ptr);
        if (!c) {
            log_addf(VTEXT(T_SKIP_LINE), l, gs->str);
            continue;
        }

        w = strtok_r(NULL, LIST_DELIM, &token_ptr);
        if (!w){
            log_addf(VTEXT(T_SKIP_LINE), l, gs->str);
            continue;
        }

       // r = strtok_r(NULL, LIST_DELIM, &token_ptr);
        r = token_ptr;

        q = g_new0(struct qso, 1);
        q->date_str = g_strdup("19900101");
        q->time_str = g_strdup("0000");
        q->callsign = g_strdup(c);
        q->mode = MOD_CW_CW;
        q->rsts=g_strdup("599");
        q->rstr=g_strdup("599");
        q->qsonrs=g_strdup_printf("%03d", l);
        q->qsonrr=g_strdup("001");
        q->exc=g_strdup("");
        q->locator = g_strdup(w);
        q->source=g_strdup(gnet->myid);
        q->operator_=aband->operator_;
        q->qrg = 0;
        q->stamp=time(NULL);
        q->remark = g_strdup(r?r:"");
		q->phase = ctest->phase;
        q->ser_id=-1; /* computed by add_qso_to_index */
        compute_qrbqtf(q);
        add_qso(aband, q);
            
        log_addf("'%s'  '%s'  '%s'", q->callsign, q->locator, q->remark);
    }
    g_string_free(gs, TRUE);
    fclose(f);
    
    g_hash_table_foreach(ctest->bystamp, foreach_source_qsort_by_stamp, NULL);
    z_ptr_array_qsort(ctest->allqsos, compare_date_time_qsonrs);
    
    for (i=0;i<ctest->bands->len;i++){
        struct band *b=(struct band *)g_ptr_array_index(ctest->bands,i);
        recalc_stats(b);
        clear_tmpqsos(b, 1);
        
        if (ctest->qsoused && b->qsos->len+1 != atoi(b->tmpqsos[0].qsonrs)){
            g_free(b->tmpqsos[0].qsonrs);
            b->tmpqsos[0].qsonrs = g_strdup_printf("%03d", b->qsos->len+1);
        }
    }
    
    return;
}
