/*
    Tucnak - VHF contest log
    Copyright (C) 2002-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 "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_cbr(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[] = {"MULTI-OP", "SINGLE-OP", "CHECKLOG"};
    char *mode[] = {"CW", "DIGI", "FM", "RTTY", "SSB", "MIXED"};
    char *ass[] = {"ASSISTED", "NON-ASSISTED", "ASSISTED"};
    int maxpower = 0;
    char *powerstr = "HIGH";
    char *cabrillo_modes[]={
        "",
        "PH",
        "CW",
        "MI",
        "MI",
        "PH",   /* 5 */
        "PH",
        "RT",
        "SS",
        "AT"  /* 9 */
    };
    char s[256];
    char t[256];
    GString *gs;
    char *categoryband = NULL;
	int complete;

    if (!ctest) return -1;
    
    dbg("export_all_bands_cbr()\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->cbr_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;

            if (categoryband == NULL){
                categoryband = band->cbr_confb->cbrband;
            }else{
                categoryband = "ALL";
            }
        }
            

        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 = "LOW";
    if (maxpower > 0 && maxpower <=10) powerstr = "QRP";

    filename = g_strdup_printf("%s/%s_%s.cbr",
                    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;
    }

    if (!categoryband) categoryband = "ALL"; // no qsos
    
    err = 0;
    fprintf(f, "START-OF-LOG: 3.0\r\n");
    fprintf(f, "CREATED-BY: %s-%s %s\r\n", PACKAGE_NAME, Z_PLATFORM, PACKAGE_VERSION);
    fprintf(f, "CONTEST: %s\r\n", ctest->tname);
    fprintf(f, "CALLSIGN: %s\r\n", ctest->pcall);
    fprintf(f, "CATEGORY-OPERATOR: %s\r\n", ope[psect%3]);
    fprintf(f, "CATEGORY-MODE: %s\r\n", mode[5]);
    fprintf(f, "CATEGORY-BAND: %s\r\n", categoryband);
    fprintf(f, "CATEGORY-POWER: %s\r\n", powerstr); 
    fprintf(f, "CATEGORY-ASSISTED: %s\r\n", ass[psect%3]);
    fprintf(f, "CATEGORY-TRANSMITTER: ONE\r\n");
    fprintf(f, "LOCATION: Write here\r\n");
    fprintf(f, "CLAIMED-SCORE: %d\r\n", ctest->allb_ntotal); 
    fprintf(f, "SPECIFIC: %s\r\n", ctest->pexch);
    fprintf(f, "CLUB: %s\r\n", ctest->pclub);
    fprintf(f, "NAME: %s\r\n", ctest->rname);
    fprintf(f, "ADDRESS: %s %s\r\n", ctest->radr1, ctest->radr2);
    fprintf(f, "ADDRESS-CITY: %s\r\n", ctest->rcity);
    fprintf(f, "ADDRESS-STATE-PROVINCE: Write here\r\n");
    fprintf(f, "ADDRESS-POSTALCODE: %s\r\n", ctest->rpoco);
    fprintf(f, "EMAIL: %s\r\n", ctest->rhbbs);
    fprintf(f, "SOAPBOX: %s\r\n", gs->str); 

	complete = (ctest->excused > 0) && (ctest->wwlused > 0) && (ctest->qsoused > 0); // UKSMG

    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->band) continue;             // maybe connot happen, I don't want to investigate
        if (!q->band->cbr_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, "%sQSO: ", q->error ? "X-" : "");
        if (q->qrg > 0 && q->qrg < 100000000){
            fprintf(f, "%5d ", (int)(q->qrg / 1000.0));
        }else{
            if (q->band->cbr_confb->qrg_min < 30000){
                fprintf(f, "%5d ", q->band->cbr_confb->qrg_min);   // 1800, 3500, 7000, 14000, 21000, 28000 
            }else if (q->band->cbr_confb->qrg_min < 1000000){
                fprintf(f, "%5d ", q->band->cbr_confb->qrg_min / 1000); // 50 144 432 902
            }else{
                fprintf(f, "%s ", padl(s, q->band->cbr_confb->cbrband, 5)); // 1.2G 2.3G 3.4G 5.7G 10G 24G 47G 75G 119G 142G 241G 300G
            }
        }
        fprintf(f, "%s ", padr(s, cabrillo_modes[q->mode], 2));

        safe_strncpy(t, q->date_str, 5);
        strcat(t, "-");
        safe_strncpy(t+5, q->date_str+4, 3);
        strcat(t, "-");
        safe_strncpy(t+8, q->date_str+6, 3);
        fprintf(f, "%s ", padr(s, t, 10));
        
        fprintf(f, "%s ", padr(s, q->time_str, 4));
        fprintf(f, "%s ", padr(s, ctest->pcall, 13));
		fprintf(f, "%s ", padr(s, q->rsts, 3));
		if (complete)
		{
			fprintf(f, "%s ", padr(s, q->qsonrs, 4));
			fprintf(f, "%s ", padr(s, ctest->pwwlo, 6));
			g_strlcpy(t, ctest->pexch, sizeof(t));
			g_strstrip(t);
			fprintf(f, "%s ", padr(s, t, strlen(ctest->pexch)));
		}else{
			if (ctest->qsoused > 0) {
				fprintf(f, "%s ", padr(s, q->qsonrs, 4));
			}
			if (ctest->wwlused > 0) {
				fprintf(f, "%s ", padr(s, ctest->pwwlo, 6));
			}
			if (ctest->excused > 0) {
				g_strlcpy(t, ctest->pexch, sizeof(t));
				g_strstrip(t);
				fprintf(f, "%s ", padr(s, t, strlen(ctest->pexch)));
			}
		//fprintf(f, "%s ", padr(s, c, 6));
		}

        fprintf(f, "%s ", padr(s, q->callsign,13));
        fprintf(f, "%s ", padr(s, q->rstr,3));
		if (complete)
		{
			fprintf(f, "%s ", padr(s, q->qsonrr, 4));
			fprintf(f, "%s ", padr(s, q->locator, 6));
			g_strlcpy(t, q->exc, sizeof(t));
			g_strstrip(t);
			fprintf(f, "%s ", padr(s, t, ctest->exclen));
		}else{
			if (ctest->qsoused > 0) {
				fprintf(f, "%s ", padr(s, q->qsonrr, 4));
			}
			if (ctest->wwlused > 0) {
				fprintf(f, "%s ", padr(s, q->locator, 6));
			}
			if (ctest->excused > 0) {
				g_strlcpy(t, q->exc, sizeof(t));
				g_strstrip(t);
				fprintf(f, "%s ", padr(s, t, ctest->exclen));
			}
		//fprintf(f, "%s ", padr(s, d, 6));
		}
        fprintf(f, "\r\n");

    }

    fprintf(f, "END-OF-LOG:\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;
}



