/*
    Tucnak - VHF contest log
    Copyright (C) 2002-2020  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 "html.h"
#include "chart.h"
#include "main.h"
#include "map.h"
#include "menu.h"
#include "qsodb.h"
#include "session.h"
#include "stats.h"
#include "tsdl.h"
#include "wiki.h"

#include <libzia.h>
#include <zjson0.h>

/*gchar *qw(GString *gs, gchar *s){
	char *c;

    g_string_truncate(gs,0);
    if (!s) return gs->str;
    
    g_string_append(gs, "<nowiki>");
	for (c=s; *c!='\0'; c++) {
        switch (*c){
            case '<':
                g_string_append(gs, "&lt;");
                break;
            case '>':
                g_string_append(gs, "&gt;");
                break;
            case '"':
                g_string_append(gs, "&quot;");
                break;
            case '&':
                g_string_append(gs, "&amp;");
                break;
            case '\'':
                g_string_append(gs, "&#39;");
                break;
            default:
                g_string_append_c(gs, *c);    
        }
    }
    g_string_append(gs, "</nowiki>");
	return gs->str;
}*/
  
void wiki_header(GString *gs){
    int i;
    
    zg_string_eprintfa("w", gs, "=%s=\n", ctest->tname);

    g_string_append_printf(gs, "{| style=\"background-color:#ffffcc;\"\n");
    zg_string_eprintfa("w", gs, "|-\n|%s||%S\n", VTEXT(T_CALL2), ctest->pcall);
    zg_string_eprintfa("w", gs, "|-\n|%s||%S\n", VTEXT(T_WWL2), ctest->pwwlo);
    if (ctest->padr1 && *ctest->padr1)
        zg_string_eprintfa("w", gs, "|-\n|%s||%s\n", VTEXT(T_QTH), ctest->padr1);
    if (ctest->padr2 && *ctest->padr2)
        zg_string_eprintfa("w", gs, "|-\n| ||%s\n", ctest->padr2);

    i = atoi(ctest->cdate);
    g_string_append_printf(gs, "|-\n|%s||%d.%d.%d\n", VTEXT(T_DATE3), i % 100, (i / 100) % 100, i / 10000);
    g_string_append_printf(gs, "|}\n");
}


static void wiki_wwl_func(gpointer key, gpointer value, gpointer user_data){
    gchar       *wwl;
    struct cntpts *n;
    ZPtrArray *ia;
    
    
    wwl   = (gchar *)       key;  
	n     = (struct cntpts *) value;
    ia    = (ZPtrArray *) user_data;

    z_ptr_array_add(ia, g_strdup_printf("%4s||align=\"right\"|\t%d||align=\"right\"|%d", wwl, n->points, n->count));
}

static gint wiki_compare_colon_int (gconstpointer a, gconstpointer b){
	gchar **ca, **cb, *c;
	int ia, ib;

	ca=(gchar **)a;
	cb=(gchar **)b;

	c=strchr(*ca, '\t');
	if (c) ia=atoi(c+1);
	else ia=0;
	c=strchr(*cb, '\t');
	if (c) ib=atoi(c+1);
	else ib=0;

	return ib-ia;
}


#define TOPS_NUM	10
void wiki_band_header(GString *gs, struct band *band, int flags){
    struct qso *q, *top[TOPS_NUM];
    int i, j, cnt = 0;
    ZPtrArray *ia;
    char *c;
	int ntotal;
    struct subwin *map = NULL;
    struct subwin *chart = NULL;
    int oldaa;
	
	if (flags & HTML_MAP) map = sw_raise_or_new(SWT_MAP);
	if (flags & HTML_CHART) chart = sw_raise_or_new(SWT_CHART);
    /*for (i = 0; i < gses->subwins->len; i++){
        struct subwin *sw = (struct subwin*)g_ptr_array_index(gses->subwins, i);
        if ((flags & HTML_MAP) && sw->type == SWT_MAP) map = sw;
        if ((flags & HTML_CHART) && sw->type == SWT_CHART) chart = sw;
    } */
#if defined(Z_HAVE_SDL) && defined(Z_HAVE_LIBPNG)
	oldaa = zsdl->antialiasing;
	if (zsdl->antialiasing_supported) zsdl->antialiasing = 1;
    
	zg_free0(band->mapfile);
    if (map && map->screen){
        map->gdirty = 1;
        map_for_photo(map, band, 0);
		map_recalc_gst(map, band);
        sw_map_redraw(map, band, HTML_FOR_PHOTO);
		band->mapfile = g_strdup_printf("%s/map%c.png", ctest->directory, tolower(band->bandchar));
		zpng_save(map->screen, band->mapfile, NULL);
    }
	zg_free0(band->chartfile);
    if (chart && chart->screen){
        chart->gdirty = 1;
        sw_chart_recalc_extremes(chart, band);
        sw_chart_redraw(chart, band, 0);
		band->chartfile = g_strdup_printf("%s/chart%c.png", ctest->directory, tolower(band->bandchar));
		zpng_save(chart->screen, band->chartfile, NULL);
    }
	if (map) map_recalc_gst(map, aband);
	zsdl->antialiasing = oldaa;
#endif
	if (chart) sw_chart_recalc_extremes(chart, aband);

    g_string_append_printf(gs, "\n\n=Band %s=\n", band->bandname);

    ntotal = band->stats->ntotal;
    if (ntotal < 10000){
        ntotal = ( ntotal / 100 ) * 100;
    }else{
        ntotal = ( ntotal / 1000 ) * 1000;
    }
    g_string_append_printf(gs, "{| style=\"background-color:#ffffcc;\"\n");
    g_string_append_printf(gs, "|+ %s\n", band->bandname);
    g_string_append_printf(gs, "|-\n|%s||%d\n", VTEXT(T_QSOS2), band->stats->nqsos);
    g_string_append_printf(gs, "|-\n|%s||%d\n", VTEXT(T_POINTS2), ntotal);
    g_string_append_printf(gs, "|-\n|%s||%d\n", VTEXT(T_WWLS), g_hash_table_size(band->stats->wwls));
    g_string_append_printf(gs, "|-\n|%s||%d\n", VTEXT(T_DXCCS), g_hash_table_size(band->stats->dxcs));
    g_string_append_printf(gs, "|-\n|%s||%d %s\n", VTEXT(T_AVG2), band->stats->ntotal/band->stats->nqsos, VTEXT(T_PTSQSO));
    g_string_append_printf(gs, "|}\n");

	/* top 10 */

	memset(top, 0, TOPS_NUM * sizeof(struct qso *));
	for (i = 0; i < band->qsos->len; i++) {
		if (!top[0]) { /* init first item */
			q = get_qso(band, i);
			if (!q->error && !q->dupe) {
				cnt = 0;
				top[cnt++] = q;
				/*dbg("init: %s %u\n=\n", top[0]->callsign, (int) top[0]->qrb);*/
			}
			continue;
		}

		q = get_qso(band, i);
		/*dbg("selected %u: %s %u\n", i, q->callsign, (int) q->qrb);*/
		if (q->error || q->dupe)
			continue;

		if (cnt >= TOPS_NUM)
			cnt = TOPS_NUM - 1;
		
		/* initialize or find top dx and sort top array */
		if (!top[cnt] || q->qrb > top[cnt]->qrb) {
			for (j = cnt; j >= 0; j--) {
				if (j && q->qrb > top[j - 1]->qrb) {
					top[j] = top[j - 1]; /* move down */
					/*dbg("down %u: %s %u\n", j, top[j]->callsign, (int) top[j]->qrb);*/
				} else {
					top[j] = q; /* insert */
					cnt++;
					/*dbg("insert %u: %s %u\n", j, top[j]->callsign, (int) top[j]->qrb);*/
					break;
				}
			}
		}
	}

    g_string_append_printf(gs, "\n\n");


    //tabulka kolem

    g_string_append_printf(gs, "{| cellpadding=\"10\" style=\"background: transparent;\"\n");
    g_string_append_printf(gs, "|\n");

    g_string_append_printf(gs, "{| cellpadding=\"5\" style=\"background-color:#ffffcc;\"\n");
    g_string_append_printf(gs, "|+ %s\n", VTEXT(T_TOP_10_CALLS));
    g_string_append_printf(gs, "!%s!!%s!!%s!!%s\n", VTEXT(T_CALL), VTEXT(T_QRB), VTEXT(T_OPERATOR2), VTEXT(T_MODE2));
	for (i = 0; i < TOPS_NUM && i < band->qsos->len && top[i]; i++) {
		q = top[i];
		g_string_append_printf(gs, "|-\n|%s||align=\"right\"|%4u km||%s||%s\n", q->callsign, (int) q->qrb, q->operator_, mode_msg[q->mode]);
	}

    g_string_append_printf(gs, "|}\n");

    ia = z_ptr_array_new();
    g_hash_table_foreach(band->stats->wwls, wiki_wwl_func, ia);
    z_ptr_array_qsort(ia, wiki_compare_colon_int);
    
    g_string_append_printf(gs, "|\n");

    g_string_append_printf(gs, "{| cellpadding=\"5\" style=\"background-color:#ffffcc;\"\n");
    g_string_append_printf(gs, "|+ %s\n", VTEXT(T_TOP_10_WWLS));
    g_string_append_printf(gs, "!%s!!%s!!%s\n", VTEXT(T_WWL3), VTEXT(T_POINTS), VTEXT(T_SW_QSOS));
    for (i = 0; i < ia->len && i < 10; i++){
        c = (gchar *)z_ptr_array_index(ia, i);
		g_string_append_printf(gs, "|-\n|%s\n", c);
    }

    g_string_append_printf(gs, "|}\n");
    z_ptr_array_free_all(ia);

    g_string_append_printf(gs, "|}\n\n");

#ifdef Z_HAVE_SDL
	if (map && map->screen){
		g_string_append_printf(gs, "[[File:map_%s_%s_%c.png|border|%dpx|%s %s %s]]\n\n", 
			ctest->pcall, ctest->cdate, z_char_lc(band->bandchar), map->screen->w,
			ctest->pcall, ctest->tname, band->bandname);
	}

	if (chart && chart->screen){
		g_string_append_printf(gs, "[[File:chart_%s_%s_%c.png|border|%dpx|%s %s %s]]\n\n", 
			ctest->pcall, ctest->cdate, z_char_lc(band->bandchar), chart->screen->w, 
			ctest->pcall, ctest->tname, band->bandname);
	}
#endif
    
}

void wiki_footer(GString *gs){
    g_string_append_printf(gs, "\n\nCreated by [http://tucnak.nagano.cz Tucnak ver. %s]\n", VERSION_STRING);
}


void wiki_complete(GString *gs, int flags){
    int i;
    struct band *band;
    int header_saved=0;

    for (i=0; i<ctest->bands->len; i++){
        band = (struct band *)g_ptr_array_index(ctest->bands, i);

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

        if (!header_saved){
            wiki_header(gs);
            header_saved=1;
        }
        wiki_band_header(gs, band, flags);
    }

    wiki_footer(gs);
}

int export_all_bands_wiki(){
    gchar *filename;
    FILE *f;
    char callbuf[20];
    GString *gs;
    
    if (!ctest) return -1;
    
    dbg("export_all_bands_wiki()\n");
	progress(VTEXT(T_EXPORTING));

	
	filename = g_strdup_printf("%s/%s_%s.wiki",
					ctest->directory,
					ctest->cdate,
					z_get_raw_call(callbuf,ctest->pcall));

	z_wokna(filename);
	f=fopen(filename,"wt");
	if (!f) {
		errbox(VTEXT(T_CANT_WRITE), errno);
		g_free(filename);
		progress(NULL);
		return -1;
	}
    
    gs = g_string_sized_new(100000);
    wiki_complete(gs, HTML_MAP | HTML_CHART);

    if (fprintf(f, "%s", gs->str) <= 0){
		errbox(VTEXT(T_CANT_WRITE), 0);
		g_free(filename);
        g_string_free(gs, TRUE);
		progress(NULL);
		return -1;
	}
	
	fclose(f);
	log_addf(VTEXT(T_SAVED_S), filename);
	g_free(filename);
    g_string_free(gs, TRUE);
	progress(NULL);
    return 0;
}

//-------- wiki upload -----------------------------------------------------------------------------------
char wiki_url[MAX_STR_LEN];
char wiki_user[MAX_STR_LEN];
char wiki_pass[MAX_STR_LEN];
char wiki_page[MAX_STR_LEN];
int wiki_map, wiki_chart, wiki_overwrite;

void free_wiki(struct wiki *wiki){
	zhttp_free(wiki->http);
	g_free(wiki->edittoken);
	zg_ptr_array_free_all(wiki->images);
	g_free(wiki);
	gses->wiki = NULL;
}

void wiki_status(struct wiki *wiki, char *fmt, ...)
{
	va_list l;
	va_start(l, fmt);

	g_free(wiki->status);
	wiki->status = g_strdup_vprintf(fmt, l);

	va_end(l);
}


void wiki_upload_callback(struct zhttp *http){
	struct wiki *wiki = (struct wiki*)http->arg;
	char *result;

    if (http->errorstr){
		wiki_status(wiki, VTEXT(T_CANT_UPLOAD_FILE_S), http->errorstr);
		zhttp_free0(wiki->http);
		return;
	}

	result = zjson0_get_str(http->datastr, -1, "upload.result");

	if (result == NULL){
		wiki_status(wiki, VTEXT(T_CANT_UPLOAD_PAGE_WIKI_RET), http->datastr);
		zhttp_free0(wiki->http);
		return;
	}
	if (strcmp(result, "Success") != 0){
		//{"upload":{"result":"Warning","warnings":{"exists":"Map_OK2M_20140503_c.png"},"filekey":"12g68l2hgzbk.9a37ay.2.png","sessionkey":"12g68l2hgzbk.9a37ay.2.png"}}
		char *exists = zjson0_get_str(http->datastr, -1, "upload.warnings.exists");
		if (exists != NULL){
			wiki_status(wiki, VTEXT(T_FILE_ALREADY_EXISTS), exists);
			g_free(exists);
		}else{
			wiki_status(wiki, VTEXT(T_CANT_UPLOAD_PAGE_RET), result);
		}
	
		zhttp_free0(wiki->http);
		g_free(result);
		return;
	}
	g_free(result);
	wiki_schedule(wiki);
}

void wiki_upload_file(struct wiki *wiki, char *localfilename, char *filename, int ignorewarnings){
	struct zhttp *http = wiki->http;

	zhttp_post_free(http);
	zhttp_post_add(http, "action", "upload");
	zhttp_post_add(http, "filename", filename);
	//zhttp_post_add(http, "text", "text");
	//zhttp_post_add(http, "comment", "Some uploaded file");
	zhttp_post_add(http, "format", "json");
	zhttp_post_add_file_disk(http, "file", filename, localfilename);
	if (ignorewarnings) zhttp_post_add(http, "ignorewarnings", "yes");
	zhttp_post_add(http, "token", wiki->edittoken);

	zhttp_post(wiki->http, zsel, wiki->apiurl, wiki_upload_callback, wiki);
}

void wiki_edit_callback(struct zhttp *http){
	struct wiki *wiki = (struct wiki*)http->arg;
	char  *result;

    if (http->errorstr){
		wiki_status(wiki, VTEXT(T_CANT_EDIT_PAGE), http->errorstr);
		zhttp_free0(wiki->http);
		return;
	}

	result = zjson0_get_str(http->datastr, -1, "edit.result");
	if (result == NULL){
		wiki_status(wiki, VTEXT(T_CANT_EDIT_PAGE_RET), http->datastr);
		zhttp_free0(wiki->http); 
		return;
	}
	if (strcmp(result, "Success") != 0){
		wiki_status(wiki, VTEXT(T_CANT_EDIT_PAGE_RET2), result);
		zhttp_free0(wiki->http); 
		g_free(result);
		return;
	}
	g_free(result);

	wiki_schedule(wiki);
}

void wiki_edit_file(struct wiki *wiki, char *title, const char *text){
	struct zhttp *http = wiki->http;
	const char *t;
	char *buf;
	iconv_t cd = iconv_open("UTF-8","ISO8859-2");
	if (cd != (iconv_t)(-1)){
		char *inptr = title;
		char *outptr;
	    size_t in = strlen(title);
		size_t out = in * 10;
		size_t ret;
		
		buf = g_new0(char, out);
		outptr = buf;

		ret = iconv(cd, &inptr, &in, &outptr, &out);
        if (ret != (size_t)-1){
    		t = buf;	 
        }else{
            t = title;
        }
	}else{
		t = title;
	}

	zhttp_post_free(http);
	zhttp_post_add(http, "action", "edit");
	zhttp_post_add(http, "title", t);
	zhttp_post_add(http, "text", text);
	zhttp_post_add(http, "assert", "user");
	zhttp_post_add(http, "format", "json");
	zhttp_post_add(http, "token", wiki->edittoken);

	zhttp_post(wiki->http, zsel, wiki->apiurl, wiki_edit_callback, wiki);
	if (cd != (iconv_t)(-1)){
		g_free(buf);
		iconv_close(cd);
	}

}

void wiki_schedule(struct wiki *wiki){
	char *localfile, *file = NULL;
	const char *f;

	if (wiki->text){
		wiki_edit_file(wiki, wiki_page, wiki->text);
		zg_free0(wiki->text);
		wiki_status(wiki, VTEXT(T_EDITING_CONTEST_PAGE));
		return;
	}

	if (wiki->images->len == 0){
		wiki_status(wiki, VTEXT(T_ALL_DONE));
		wiki->done = 1;
		return;
	}

	localfile = (char *)g_ptr_array_index(wiki->images, 0);
	g_ptr_array_remove_index(wiki->images, 0);

	f = z_filename(localfile);
	if (strncmp(f, "map", 3) == 0){
		file = g_strdup_printf("map_%s_%s_%c.png", ctest->pcall, ctest->cdate, f[3]);
	}
	if (strncmp(f, "chart", 5) == 0){
		file = g_strdup_printf("chart_%s_%s_%c.png", ctest->pcall, ctest->cdate, f[5]);
	}

	if (file != NULL){
		wiki_upload_file(wiki, localfile, file, wiki_overwrite);
		wiki_status(wiki, VTEXT(T_UPLOADING_FILE), f);
	}else{
		wiki_status(wiki, VTEXT(T_UNKNOWN_FILE_FOR_UPLOAD), localfile);
	}

	g_free(localfile);
	g_free(file);
}

// old API about 1.19
void wiki_query_edittoken(struct zhttp *http){
	struct wiki *wiki = (struct wiki*)http->arg;

    if (http->errorstr){
		wiki_status(wiki, VTEXT(T_CANT_QUERY_EDIT_TOKEN), http->errorstr);
		zhttp_free0(wiki->http); 
		return;
	}
	
//{"query":{"pages":{"-1":{"ns":0,"title":"Main Page","missing":"","starttimestamp":"2014-07-15T06:21:10Z","edittoken":"43cf06841bc074e7922cece1617f1504+\\"}}}}
	wiki->edittoken = zjson0_get_str(http->datastr, -1, "query.pages.-1.edittoken");
	if (wiki->edittoken == NULL){
		wiki_status(wiki, VTEXT(T_CANT_QUERY_EDIT_TOKEN_RET), wiki);
		zhttp_free0(wiki->http);
		return;
	}
		
	wiki_schedule(wiki);
}

void wiki_logged_in(struct wiki *wiki){
	GString *gs;
	
	gs = g_string_new(wiki->apiurl);
	//zg_string_eprintfa("u", gs, "api.php?action=tokens&type=edit&format=json");  new API
	zg_string_eprintfa("u", gs, "?action=query&format=json&type=import&prop=info|revisions&intoken=edit&titles=%s", "Main Page");
	zhttp_post(wiki->http, zsel, gs->str, wiki_query_edittoken, wiki);
	g_string_free(gs, TRUE);

	wiki_status(wiki, VTEXT(T_QUERYING_EDIT_TOKEN));
}

void wiki_login2(struct zhttp *http){
    struct wiki *wiki = (struct wiki*)http->arg;
	char *result;

    if (http->errorstr){
		wiki_status(wiki, VTEXT(T_CANT_LOGIN), http->errorstr);
		zhttp_free0(wiki->http);
		return;
	}
	
	result = zjson0_get_str(http->datastr, -1, "login.result");
	if (result != NULL && strcmp(result, "Success") == 0){
		wiki_logged_in(wiki);
	}else{
		wiki_status(wiki, VTEXT(T_CANT_LOGIN2), result);
	}
	g_free(result);
}

void wiki_login1(struct zhttp *http){
    struct wiki *wiki = (struct wiki*)http->arg;
	char *result, *token;

    if (http->errorstr){
		wiki_status(wiki, VTEXT(T_CANT_LOGIN1), http->errorstr);
		zhttp_free0(wiki->http); 
		return;
	}
	

	// html={"login":{"result":"NeedToken","token":"b03a54f2c660eae532eaaab9a272973b","cookieprefix":"wiki_krq","sessionid":"99611b7e82e04d8a7e2542030d5f18a1"}}
	result = zjson0_get_str(http->datastr, -1, "login.result");
	token = zjson0_get_str(http->datastr, -1, "login.token");
	if (strcasecmp(result, "NeedToken") == 0){
		GString *gs = g_string_new(wiki->apiurl);
		zg_string_eprintfa("u", gs, "?action=login&format=json&lgname=%s&lgpassword=%s&lgtoken=%s", wiki_user, wiki_pass, token);
		zhttp_post(wiki->http, zsel, gs->str, wiki_login2, wiki);
		g_string_free(gs, TRUE);
	}else{
		wiki_logged_in(wiki);
	}
	g_free(result);
	g_free(token);
}


void wiki_export(void *arg){
	int i;
	int flags = 0;
    struct wiki *wiki = (struct wiki*)arg;
	GString *gs = g_string_new("");

	redraw();

	wiki->http = zhttp_init();

	if (wiki_map) flags |= HTML_MAP;
	if (wiki_chart) flags |= HTML_CHART;
	wiki_complete(gs, flags);
	wiki->text = g_strdup(gs->str);

	
	for (i=0; i<ctest->bands->len; i++){
		struct band *b = (struct band *)g_ptr_array_index(ctest->bands, i);
		if (b->mapfile) g_ptr_array_add(wiki->images, g_strdup(b->mapfile));
		if (b->chartfile) g_ptr_array_add(wiki->images, g_strdup(b->chartfile));
	}
   
	g_string_truncate(gs, 0);
	g_string_append(gs, wiki_url);
	if (gs->len > 0 && gs->str[gs->len - 1] != '/') g_string_append_c(gs, '/');
	g_string_append(gs, "api.php");
	wiki->apiurl = g_strdup(gs->str);

	zg_string_eprintfa("u", gs, "?action=login&format=json&lgname=%s&lgpassword=%s", wiki_user, wiki_pass);
	zhttp_post(wiki->http, zsel, gs->str, wiki_login1, wiki);
	g_string_free(gs, TRUE);

	wiki_status(wiki, VTEXT(T_LOGGING_IN));
}

void wiki_refresh_upload(void *xxx){
	struct wiki *wiki;
	
	STORE_STR(cfg, wiki_url);
	STORE_STR(cfg, wiki_user);
	STORE_STR(cfg, wiki_pass);
	STORE_INT(cfg, wiki_map);
	STORE_INT(cfg, wiki_chart);

	wiki = g_new0(struct wiki, 1);
	wiki->images = g_ptr_array_new();
	gses->wiki = wiki;

	wiki_status(wiki, VTEXT(T_EXPORTING_FILES));
	wiki_info(NULL);
	zselect_bh_new(zsel, wiki_export, wiki);
}

void wiki_upload(void *arg){
	struct dialog *d;
	int i;

	if (!ctest) return;
	if (gses->wiki != NULL) return;

	safe_strncpy0(wiki_url, cfg->wiki_url, MAX_STR_LEN);
	safe_strncpy0(wiki_user, cfg->wiki_user, MAX_STR_LEN);
	safe_strncpy0(wiki_pass, cfg->wiki_pass, MAX_STR_LEN);
	safe_strncpy0(wiki_page, ctest->tname, MAX_STR_LEN);
	wiki_map = 1;
	wiki_chart = 1;

	if (!(d = (struct dialog *) g_malloc(sizeof(struct dialog) + 55 * sizeof(struct dialog_item)))) return;
    memset(d, 0, sizeof(struct dialog) + 55 * sizeof(struct dialog_item));
    d->title = VTEXT(T_NETWORK);
    d->fn = dlg_pf_fn;
    d->refresh = (void (*)(void *))wiki_refresh_upload;
    d->y0 = 1;
	i = -1;
    
    d->items[++i].type = D_FIELD;     
    d->items[i].dlen = MAX_STR_LEN;
    d->items[i].data = wiki_page;
    d->items[i].maxl = 44;
    d->items[i].msg = CTEXT(T_PAGE_NAME);
	d->items[i].wrap = 1;

	d->items[++i].type = D_CHECKBOX;  
    d->items[i].gid = 0;
    d->items[i].gnum = 1;
    d->items[i].dlen = sizeof(int);
	d->items[i].data = (char *)&wiki_overwrite;
    d->items[i].msg = CTEXT(T_OVERWRITE_EXISTING_FILES);
	d->items[i].wrap = 2;
    
    d->items[++i].type = D_FIELD;     
    d->items[i].dlen = MAX_STR_LEN;											   
    d->items[i].data = wiki_url;
    d->items[i].maxl = 44;
    d->items[i].msg = CTEXT(T_SITE_URL);
    d->items[i].wrap = 1;

    d->items[++i].type = D_FIELD;     
    d->items[i].dlen = MAX_STR_LEN;
    d->items[i].data = wiki_user;
    d->items[i].maxl = 16;
    d->items[i].msg = CTEXT(T_USERNAME);
    //d->items[i].wrap = 1;

    d->items[++i].type = D_FIELD;     
    d->items[i].dlen = MAX_STR_LEN;
    d->items[i].data = wiki_pass;
    d->items[i].maxl = 16;
    d->items[i].msg = CTEXT(T_PASSWORD2);
    d->items[i].wrap = 1;

	d->items[++i].type = D_CHECKBOX;  
    d->items[i].gid = 0;
    d->items[i].gnum = 1;
    d->items[i].dlen = sizeof(int);
    d->items[i].data = (char *)&wiki_map;
    d->items[i].msg = CTEXT(T_EXPORT_MAP);
	d->items[i].wrap = 1;
    
	d->items[++i].type = D_CHECKBOX;  
    d->items[i].gid = 0;
    d->items[i].gnum = 1;
    d->items[i].dlen = sizeof(int);
    d->items[i].data = (char *)&wiki_chart;
    d->items[i].msg = CTEXT(T_EXPORT_CHART);
	d->items[i].wrap = 1;
   

	d->items[i].wrap++;
	d->items[++i].type = D_BUTTON;
    d->items[i].gid = B_ENTER;
    d->items[i].fn = ok_dialog;
    d->items[i].text = VTEXT(T_OK);
    
    d->items[++i].type = D_BUTTON;
    d->items[i].gid = B_ESC;
    d->items[i].fn = cancel_dialog;
    d->items[i].text = VTEXT(T_CANCEL);
    d->items[i].align = AL_BUTTONS;
    d->items[i].wrap = 1;
    
    
    d->items[++i].type = D_END;
    do_dialog(d, getml(d, NULL));
}


void wiki_abort(void *arg){
	if (!gses->wiki) return;
	free_wiki(gses->wiki);
	gses->wiki = NULL;
}

void wiki_info(void *arg1){
	struct refresh *r;
	char *c, *button;
	GString *gs;
							    
	if (!gses || !gses->wiki) return;

	if (term->windows.next->handler	== menu_func){
		zselect_timer_new(zsel, RESOURCE_INFO_REFRESH, wiki_info, NULL);
	}else{
		r = (struct refresh*)g_malloc(sizeof(struct refresh));
		r->win = NULL;
		r->fn = wiki_info;
		r->data = NULL;
		r->timer = -1;

		gs = g_string_new("");
		if (gses->wiki->status != NULL) g_string_append_printf(gs, "%s", gses->wiki->status);
		if (gses->wiki->status != NULL && gses->wiki->http != NULL) g_string_append(gs, "\n\n");
		if (gses->wiki->http != NULL){
			g_string_append(gs, VTEXT(T_HTTP_STATUS));
			zhttp_status(gses->wiki->http, gs);
		}
		button = gses->wiki->done ? VTEXT(T_OK) : VTEXT(T_CANCEL);
		c = g_strdup(gs->str);
		g_string_free(gs, TRUE);

		msg_box(getml(c, NULL), VTEXT(T_MEDIAWIKI_UPLOAD2)/*VTEXT(T_NINFO)*/, AL_LEFT, c, r, 1, button, wiki_abort, B_ENTER | B_ESC);
		r->win = term->windows.next;
		((struct dialog_data *)r->win->data)->dlg->abort = refresh_abort;
		r->timer = zselect_timer_new(zsel, RESOURCE_INFO_REFRESH, (void (*)(void *))refresh, r);
	}
}

