/*
    Tucnak - VHF contest log
    Copyright (C) 2002-2020  Ladislav Vaiz <ok1zia@nagano.cz>
    2020 Michal OK2MUF

    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 "language2.h"
#include "net.h"
#include "qsodb.h"
#include "stats.h"
#include "tsdl.h"
#include "tregex.h"
#include "sota.h"

static int convert_to_sota_date(char *cdout, char *cdin)
{
    /* 20201025 to 25/10/2020 */
    int year, month, day;
    sscanf(cdin, "%4d%2d%2d", &year, &month, &day);
	return g_snprintf(cdout, 12, "%02d/%02d/%04d", day, month, year);
}

static int convert_to_sota_time(char *ctout, char *ctin)
{
    /* 1922 to 19:22 */
    int sec, hour;
    sscanf(ctin, "%2d%2d", &hour, &sec);
	return g_snprintf(ctout, 6, "%02d:%02d", hour, sec);
}

static int convert_to_sota_band(char *cbandout, char *cbandin)
{
    if (cbandin == NULL || cbandout == NULL)
        return -1;

    while (*cbandin != '\0')
    {
        if (*cbandin != ' ')
            *cbandout++ = toupper(*cbandin);
        cbandin++;
    }
    *cbandout = '\0';

    return 1;
}

static int write_sota_qsos(char *sotaref, struct band *b, struct config_band *confb, FILE *f){
    struct qso *q;
    GString *gs;
    int i;
    int ret;
    //char s[1024];
    char sota_date[12];
    char sota_time[6];
    char sota_band[12];
        

    gs = g_string_new("");
    
    
    for (i=0; i<b->qsos->len; i++){
        q = get_qso(b, i); 

        if (q->error || q->dupe)
            continue;

        convert_to_sota_band(sota_band, b->pband);
        convert_to_sota_date(sota_date, q->date_str);
        convert_to_sota_time(sota_time, q->time_str);

        g_string_append_printf(gs, "V2,%s,%s,%s,%s,%s,%s,%s,%s,\"RSTrcvd: %s RSTsnd: %s",
            ctest->pcall,
            sotaref,
            sota_date,
            sota_time,
            sota_band,
            get_sota_mode_ps(q->mode),
            q->callsign,
            q->exc,
            q->rstr,
            q->rsts
        );
        if (q->locator && strlen(q->locator))
            g_string_append_printf(gs, " GRID: %s", q->locator);
        
        g_string_append(gs, "\"\n");

    }
    
    ret=fprintf(f, "%s", gs->str) != gs->len;
    g_string_free(gs, TRUE);
    
    return ret;
}

char* get_sota_mode_ps(int mode){
    static char *sota_modes[]={
        "",
        "SSB",
        "CW",
        "SSB",
        "SSB",
        "AM",   /* 5 */
        "FM",
        "DATA",
        "DATA",
        "Other"  /* 9 */
    };
    return sota_modes[abs(mode)%10];
}

gchar* get_sota_log_filename(void)
{
    char callbuf[20];
    /*  !!! Do not forgot free returned g_string by g_free() !!! */
    return g_strdup_printf("%s/%s_%s.csv",
                    ctest->directory,
                    ctest->cdate,
                    z_get_raw_call(callbuf,ctest->pcall));
}

int export_all_bands_sota(void){
    struct band *band;
    struct config_band *confb;
    int i, err;
    gchar *filename;
    FILE *f;
    int ignoreerror=0;
    //int header_saved=0;
    
    if (!ctest) return -1;
    
    dbg("export_all_bands_sota()\n");
    /*
    if (!regcmpi(ctest->tname, "[a-zA-Z0-9]{2,3}/[a-zA-Z0-9]{2,3}-[0-9]{3}"))
        log_addf("No reference in contest name");
    */
    if (!strlen(ctest->pexch))
        log_addf("Empty SOTA reference in contest settings (exc)");

    filename = get_sota_log_filename();
    z_wokna(filename);    
    f=fopen(filename,"wb"); /* must be b for windoze */
    if (!f) {
        if (!ignoreerror) { errbox(VTEXT(T_CANT_WRITE), errno); ignoreerror=1;}
        g_free(filename);
        return -1;
    }
    
    err = 0;
    
    for (i=0; i<ctest->bands->len; i++){
        band = g_ptr_array_index(ctest->bands, i);
        confb = get_config_band_by_bandchar(band->bandchar);

        progress(VTEXT(T_EXPORTING_S), band->bandname);

        stats_thread_join(band);
        if (band->stats->nqsos <=0) continue;

        err|=write_sota_qsos(ctest->pexch,band,confb,f); /* TODO: get ref from contest name */
    }
    
    fclose(f);
    if (err) {
        if (!ignoreerror) { errbox(VTEXT(T_CANT_WRITE), 0); ignoreerror=1; }
        g_free(filename);
        progress(NULL);
        return -1;
    }
    log_addf(VTEXT(T_SAVED_S), filename);
    g_free(filename);
    progress(NULL);
    return 0;
}
