/*
 *                         R E S O U R C E . C
 *
 *  Implements the resoruce command.
 *  -  create and display popup
 *  -  send data
 *  -  process answer
 *
 *  Version      : $Revision: 1.6 $
 *
 *  Created      : Fri Jun 17 19:24:09 1994
 *  Author       : Ulrich Drepper <drepper@mydec>
 *
 *  Last modified: Thu Jul 14 02:01:18 1994
 *  Author       : Ulrich Drepper <drepper@mydec>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 1, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */
#if !defined(lint)
static const char *vcid = "$Id: resource.c,v 1.6 1994/07/14 09:34:56 drepper Exp $";
#endif /* lint */

#include <assert.h>
#include <ctype.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>
#include <X11/Xaw/AsciiText.h>
#include <X11/Xaw/Command.h>
#include <X11/Xaw/Form.h>
#include <X11/Xaw/Toggle.h>

#include "empire.h"

/*
 * prototypes of local functions
 */
static void commandInitResource(void);
static void resourceEditAdd(Bool active, XawTextBlock *textBlock, Bool async);
static void callbackResource(Widget widget, XtPointer closure,
			     XtPointer callData);
static void resourceNotify(Widget w, XEvent *event, String *params,
			   Cardinal *numParams);
static Bool processResource(Bool first, Bool last, char *str, void *data);

/*
 * local variables
 */
static Widget resourcePopup;
static Widget form;
static Widget sectorText;
static Widget okButton;
static void (*oldEditAdd)(Bool, XawTextBlock *, Bool);

/*
 * exported functions
 */
void
queryCommandResource(void)
{
    static Bool firstCall = True;
    Position fx, fy;
    Position x, y;

    if (firstCall) {
	commandInitResource();
	firstCall = False;
    }

    XtVaGetValues(
	commandForm,
	XtNx, &fx,
	XtNy, &fy,
	NULL);

    XtVaGetValues(
	horizPane,
	XtNx, &x,
	XtNy, &y,
	NULL);

    XtTranslateCoords(
	topLevel,
	x+fx, y+fy,
	&x, &y);

    XtVaSetValues(
	resourcePopup,
	XtNx, x,
	XtNy, y,
	NULL);

    /* prepare edit widget communication */
    oldEditAdd = currentEditAdd;
    oldEditAdd(False, NULL, False);

    currentEditAdd = resourceEditAdd;
    currentEditAdd(True, NULL, False);
    
    XawTextSetInsertionPoint(sectorText, 0);
    XtVaSetValues(
	sectorText,
        XtNstring, "",
        NULL);

    XtPopup(resourcePopup, XtGrabNonexclusive);
    XtAddGrab(showViewport, False, False);
}

Bool
resourceCommand(int xMin, int yMin, int xMax, int yMax, Bool redisplay)
{
    return sendCmdStr(processResource, (void*)redisplay, NULL,
		      "resource %d:%d,%d:%d\n", xMin, xMax, yMin, yMax);
}

/*
 * local functions
 */

static void
commandInitResource(void)
{
    static String textTranslations = 
	"#override\n"
	"<Key>Return: resourceNotify()\n"
	"<Key>Linefeed: resourceNotify()\n"
	"Ctrl<Key>M: resourceNotify()\n"
	"Ctrl<Key>J: resourceNotify()\n";
    static XtActionsRec defaultAction[1] = {
	{ "resourceNotify", resourceNotify },
    };
    XtTranslations textTrans;
    Widget tmp;

    XtAppAddActions(appContext, defaultAction, 1);
    textTrans = XtParseTranslationTable(textTranslations);

    resourcePopup =  XtVaCreatePopupShell(
	"resourcepopupshell",
	topLevelShellWidgetClass,
	topLevel,
	NULL);
    form = XtVaCreateManagedWidget(
	"form",
	formWidgetClass,
	resourcePopup,
	NULL);
    tmp = XtVaCreateManagedWidget(
	"resource",
	labelWidgetClass,
	form,
	NULL);
    tmp = XtVaCreateManagedWidget(
	"sectorlabel",
	labelWidgetClass,
	form,
	NULL);
    sectorText = XtVaCreateManagedWidget(
	"sectortext",
	asciiTextWidgetClass,
	form,
	XtNeditType, XawtextEdit,
	XtNtranslations, textTrans,
	NULL);

    okButton = XtVaCreateManagedWidget(
	"OK",
	commandWidgetClass,
	form,
	NULL);
    XtAddCallback(
	okButton,
	XtNcallback, callbackResource,
	(XtPointer)True);
    tmp = XtVaCreateManagedWidget(
	"Cancel",
	commandWidgetClass,
	form,
	NULL);
    XtAddCallback(
	tmp,
	XtNcallback, callbackResource,
	(XtPointer)False);

    XtRealizeWidget(resourcePopup);
}

/* ARGSUSED */
static void
resourceEditAdd(Bool active, XawTextBlock *textBlock, Bool async)
{
    assert(async==False);
    if (textBlock) {
	XtVaSetValues(
	    sectorText,
	    XtNstring, textBlock->ptr,
	    NULL);
	XawTextSetInsertionPoint(sectorText, strlen(textBlock->ptr));
    } else {
	XawTextDisplayCaret(sectorText, active);
	if (active) {
	    XtSetKeyboardFocus(form, sectorText);
	    XtSetKeyboardFocus(vertPane, sectorText);
	}
    }
}

static void
callbackResource(Widget widget, XtPointer closure, XtPointer callData)
{
    XtPopdown(resourcePopup);

    currentEditAdd(False, NULL, False);
    currentEditAdd = oldEditAdd;
    oldEditAdd(True, NULL, False);
    
    if ((Bool)closure) {
	char *sector;
	int x1, y1, x2, y2;
	
	XtVaGetValues(
	    sectorText,
	    XtNstring, &sector,
	    NULL);

	if (strToRange(&sector, &x1, &y1, &x2, &y2)) {
	    resourceCommand(x1, y1, x2, y2, True);
	}
    }
}

/* ARGSUSED */
static void
resourceNotify(Widget w, XEvent *event, String *params, Cardinal *numParams)
{
    XtCallActionProc(okButton, "set", NULL, NULL, 0);
    XtCallActionProc(okButton, "notify", NULL, NULL, 0);
    XtCallActionProc(okButton, "unset", NULL, NULL, 0);
}

static Bool
processResource(Bool first, Bool last, char *str, void *data)
{
#define RESOURCEHEADERLINES 3
    static dataLine = 0;
    static XRectangle rectangle;
    Bool redisplay = (Bool)data;
    int x, y;
    EmpireSector *sector;
    int tmp;

    if (first) {
	dataLine = 0;
    }    /* we determine it each time new */

    if (last) {
	if (redisplay && dataLine > RESOURCEHEADERLINES) {
	 redisplaySectors(mapWidget, rectangle.x, rectangle.y,
			     rectangle.width, rectangle.height);
	}
	return True;
    }

    if (++dataLine<=RESOURCEHEADERLINES || !isspace(str[0])) return True;

    /* First info is coord */
    strToCoord(&str, &x, &y);

    /* combine to minimal rectangle */
    if (dataLine == RESOURCEHEADERLINES+1) {
	rectangle.x = x;
	rectangle.y = y;
	rectangle.width = x;
	rectangle.height = y;
    } else {
	rectangle.x = min(rectangle.x,x);
	rectangle.width = max(rectangle.width,x);
	rectangle.y = min(rectangle.y,y);
	rectangle.height = max(rectangle.height,y);
    }

    /* change to array base */
    x = MAP2ARRX(x);
    y = MAP2ARRY(y);

    /* we can access the sector */
    sector = &empire.map[x+y*empire.rowBytes];

    /* next is the designation */
    while (isspace(*str)) str++;
    sector->typeChar = *str++;
    sector->status = OwnSector;
    sector->typePixmap = getTypePixmap(x, y, OwnSector, False);

    /* efficience */
    strToInt(&str, &tmp);
    sector->eff = tmp;
    str++;                          /* the % sign */
    
    sscanf(str, "%d %d %d %d %d %d",
	   &sector->resource[resIdxMin],
	   &sector->resource[resIdxGold],
	   &sector->resource[resIdxFert],
	   &sector->resource[resIdxOil],
	   &sector->resource[resIdxUran],
	   &tmp);                      /* FIX ME: what is territory number */

    return True;
}

/*
 * Local Variables:
 *  mode:c
 *  c-indent-level:4
 *  c-continued-statement-offset:4
 *  c-continued-brace-offset:0
 *  c-brace-offset:0
 *  c-imaginary-offset:0
 *  c-argdecl-indent:4
 *  c-label-offset:-2
 * End:
 */
