/*
    Tucnak - VHF contest log
    Copyright (C) 2002-2020  Ladislav Vaiz <ok1zia@nagano.cz>
                             Florian Wolters <df2et@df2et.de>

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

static char *padr(char *dst, const char *src, int len){
    int l;
    memset(dst, ' ', len);
    l = strlen(src);
    if (l > len) l = len;
    memcpy(dst, src, l);
    dst[len] = '\0';
    return dst;
}

static char *padl(char *dst, const char *src, int len){
    int l;
    memset(dst, ' ', len);
    l = strlen(src);
    if (l > len) l = len;
    memcpy(dst + len - l, src, l);
    dst[len] = '\0';
    return dst;
}

int export_all_bands_stf(void){
    int i, err;
    gchar *filename;
    FILE *f;
    char callbuf[20];
    int ignoreerror=0;
    int psect = 2; // 0=Multi, 1=Single, 2=Check
    char *ope[] = {"MM", "SO", "CHECK"};
    char *ass[] = {"(A)", "", "(A)"};
    int maxpower = 0;
    char *powerstr = "HP";
    char *cabrillo_modes[]={
        "",
        "SSB",
        "CW",
        "SSB",
        "CW",
        "AM",
        "FM",
        "RTTY",
        "SSTV",
        "ATV"
    };
    char s[256];
    char t[256];
    GString *gs;
    time_t now;

    if (!ctest) return -1;
    
    dbg("export_all_bands_stf()\n");
	progress(VTEXT(T_EXPORTING));

    
    gs = g_string_sized_new(1024);
    for (i=0; i<cfg->bands->len;i++){
        struct config_band *cb=(struct config_band *)g_ptr_array_index(cfg->bands, i);
        struct band *band = find_band_by_bandchar(cb->bandchar);
        if (!band) continue;
        band->stf_confb = cb;

        stats_thread_join(band);
        if (band->stats->nqsos > 0){
			int p;
            dbg("band %c psect = %d\n", band->bandchar, psect);
            if (band->psect < psect) psect = band->psect;  // check has priority. It's not optimal but...
            dbg("band %c psect = %d\n", band->bandchar, psect);
            p = atoi(band->spowe);
            if (p > maxpower) maxpower = p;
        }
            

        dbg("band %c remarks = %s\n", band->bandchar, band->remarks);
        if (strlen(band->remarks) > 0){
            if (gs->len > 0) g_string_append_c(gs, ' ');
            g_string_append(gs, band->remarks);
        }
    }

    if (maxpower > 0 && maxpower <=100) powerstr = "LP";
    if (maxpower > 0 && maxpower <=10) powerstr = "QRP";

    filename = g_strdup_printf("%s/%s_%s.stf",
                    ctest->directory,
                    ctest->cdate,
                    z_get_raw_call(callbuf,ctest->pcall));
        
	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);
        g_string_free(gs, 1);
		progress(NULL);
        return -1;
    }

    err = 0;
    time(&now);
    fprintf(f, "STF1\r\n");
    fprintf(f, "# Created by %s-%s %s\r\n", PACKAGE_NAME, Z_PLATFORM, PACKAGE_VERSION);
    fprintf(f, "# File written %s", asctime(gmtime(&now)));
    fprintf(f, "# STF specs at www.darcdxhf.de\r\n");
    fprintf(f, "Header\r\n");
    fprintf(f, "Contest      %s\r\n", ctest->tname);
    fprintf(f, "MyCall       %s\r\n", ctest->pcall);
    fprintf(f, "Category     %s%s%s\r\n", ope[psect%3], powerstr, ass[psect%3]);
    fprintf(f, "MailAddress  %s\r\n", ctest->rname);
    fprintf(f, "MailAddress  %s %s\r\n", ctest->radr1, ctest->radr2);
    fprintf(f, "MailAddress  %s %s\r\n", ctest->rpoco, ctest->rcity);
    fprintf(f, "EMail        %s\r\n", ctest->rhbbs);
    fprintf(f, "ClaimedQso   %d\r\n", ctest->allb_nqsos);
    fprintf(f, "ClaimedPts   %d\r\n", ctest->allb_nqsop);
    fprintf(f, "ClaimedMult  %d\r\n", ctest->allb_nexcp);
    fprintf(f, "ClaimedScore %d\r\n", ctest->allb_ntotal);
    fprintf(f, "Club         %s\r\n", ctest->pclub);
    fprintf(f, "Power        %d\r\n", maxpower);
    fprintf(f, "QsoOrder Date Time Band Mode Call SRst Sent Sent2 RRst Rcvd Rcvd2 Pts Mult Mult2\r\n");
    fprintf(f, "EndHeader\r\n");


    fprintf(f, "\r\n"); 
    fprintf(f, "QsoList: %s\r\n", gs->str); 

    for (i=0; i<ctest->allqsos->len; i++){
        struct qso *q = (struct qso *)z_ptr_array_index(ctest->allqsos, i);
        char *d = NULL;
        if (q->error) continue;
        if (!q->band) continue;             // maybe connot happen, I don't want to investigate
        if (!q->band->stf_confb) continue;


        d = NULL;
        if (!d && ctest->excused && strlen(q->exc) > 0)     d = q->exc;
        if (!d && ctest->wwlused && strlen(q->locator) > 0) d = q->locator;
        if (!d && ctest->qsoused && strlen(q->qsonrr) > 0)  d = q->qsonrr;
        if (!d && strlen(q->exc) > 0)     d = q->exc;
        if (!d && strlen(q->locator) > 0) d = q->locator;
        if (!d && strlen(q->qsonrr) > 0)  d = q->qsonrr;
        if (!d) d = "      "; 
        


        fprintf(f, "%s ", q->date_str);
        fprintf(f, "%s ", padr(s, q->time_str, 4));
        if (q->qrg > 0 && q->qrg < 100000000){
            fprintf(f, "%5d ", (int)(q->qrg / 1000.0));
        }else{
	    fprintf(f, "%3d ", q->band->stf_confb->stfband);
        }
        fprintf(f, "%s ", padr(s, cabrillo_modes[q->mode], 4));
        fprintf(f, "%s ", padr(s, q->callsign,13));
	fprintf(f, "%s ", padr(s, q->rsts, 3));
	g_strlcpy(t, ctest->pexch, sizeof(t));
	g_strstrip(t);
	fprintf(f, "%s ", padr(s, t, strlen(ctest->pexch)));
	fprintf(f, "%s ", padr(s, ctest->pwwlo, 6));
        fprintf(f, "%s ", padr(s, q->rstr,3));
	g_strlcpy(t, q->exc, sizeof(t));
	g_strstrip(t);
	if(strlen(t) > 0) {
		fprintf(f, "%s ", padr(s, t, ctest->exclen));
	} else {
		fprintf(f, "%s ", padr(s, "-", ctest->exclen));
	}
	if(strlen(q->locator) > 0) {
		fprintf(f, "%s ", padr(s, q->locator, 6));
	} else {
		fprintf(f, "%s ", padr(s, "-", 6));
	}
	fprintf(f, "  %d ", q->qsop);
	if(q->new_ & NEW_EXC) {
		fprintf(f, "%s ", padr(s, q->exc, 3));
	} else {
		fprintf(f, "-   ");
	}
	fprintf(f, "%s ", padl(s, "-", 3));
        fprintf(f, "\r\n");

    }

    fprintf(f, "EndQsoList\r\n");

    fclose(f);
    if (err) {
        if (!ignoreerror) { errbox(VTEXT(T_CANT_WRITE), 0); ignoreerror=1; }
        g_free(filename);
        g_string_free(gs, 1);
		progress(NULL);
        return -1;
    }
    log_addf(VTEXT(T_SAVED_S), filename);
    g_free(filename);
    g_string_free(gs, 1);
	progress(NULL);
    return 0;
}



