/**
*** XPG - Graphical User Interface for Postgres
*** Copyright (C) 1993  Ranen Goren (ranen@cs.huji.ac.il).

*** 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 2 of the License, 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.
**/


#include <stdio.h>
#include <string.h>
#include <varargs.h>
#include <math.h>
#include <X11/StringDefs.h>
#include <X11/Intrinsic.h> 
#include <X11/cursorfont.h>
#include <Xm/Xm.h>
#include <Xm/Form.h>
#include <Xm/RowColumn.h>
#include <Xm/PushB.h>
#include <Xm/PushBG.h>
#include <Xm/ToggleBG.h>
#include <Xm/LabelG.h>
#include <Xm/Label.h>
#include <Xm/Frame.h>
#include <Xm/Separator.h>
#include <Xm/ScrolledW.h>
#include "xpg.h"

#define String JUST_A_DUMB_STRING
#include "tmp/libpq.h"       /* postgres */
#undef String

#ifdef MEM_DEBUG
#include "/CS/system/ranen/Src/Lib/Malloc/malloc.h"
#endif




void helpView();
Widget openClassOpsShell();
void mathOpsCancel();
void mathOk();



/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
mathOps(rel)
  relInfo *rel;
{
    Widget sh, sw, fieldsForm, text_w, form, copBox;
    Widget update, cancel, but, label;
    Widget top, toggleBox, frame;
    XmString compStr;
    PortalBuffer *p;
    Widget *fields;
    int i, m, n;
    mathCbsStruct *cbs;
    
    setCursor(rel->top, XC_watch);
    p = PQparray(rel->portal);
    n = PQntuples(p);
    if (rel->attrInfo)
	free(rel->attrInfo);
    if (!(m = getFieldInfo(rel, &(rel->attrInfo), IGNORE_LENGTH, 
			   CONSIDER_FIELD_NAMES)))
	return 1;
    if (((fields = (Widget *)calloc(m+2, sizeof(char *))) == NULL) ||
	((cbs = (mathCbsStruct *)malloc(sizeof(mathCbsStruct))) == NULL))
	     XtError("Mem error!");
    cbs->action = SUM;       /* default */
    cbs->allAttr = True;     /* default */
    cbs->allTuples = True;   /* default */
    cbs->rel = rel;
    cbs->numFields = m;
    cbs->fields = fields;
    cbs->results = NULL;
    cbs->opsSh = sh = openClassOpsShell(rel->top, "mathOps");
    copBox = XtVaCreateManagedWidget("copBox",
				     xmFormWidgetClass, sh, NULL);
    XtAddCallback(copBox, XmNhelpCallback, helpView, "math operations");
    sw = XtVaCreateManagedWidget("copSW", xmScrolledWindowWidgetClass, 
				 copBox,
				 XmNscrollingPolicy,  XmAUTOMATIC,
				 XmNvisualPolicy, XmVARIABLE,
				 NULL);
    fieldsForm = XtVaCreateManagedWidget("copFields", xmFormWidgetClass,sw,
					 NULL);
    top = NULL;
    for (i = ATTR_1ST(rel); i<m; i++) 
    {
        form = XtVaCreateWidget("copForm", xmFormWidgetClass, fieldsForm,
				XmNfractionBase,  10,
				XmNleftAttachment,   XmATTACH_FORM,
				XmNrightAttachment,  XmATTACH_FORM,
				XmNtopAttachment,    
				(top ? XmATTACH_WIDGET : XmATTACH_FORM),
				XmNtopWidget,        top,
				NULL);
	top = form;  /* for the next widget */
	compStr = XmStringCreateSimple(rel->attrInfo[i].name);
        XtVaCreateManagedWidget("copLabel",
				xmLabelGadgetClass, form,
				XmNlabelString,      compStr,
				XmNtopAttachment,    XmATTACH_FORM,
				XmNbottomAttachment, XmATTACH_FORM,
				XmNleftAttachment,   XmATTACH_FORM,
				XmNrightAttachment,  XmATTACH_POSITION,
				XmNrightPosition,    3,
				XmNalignment,        XmALIGNMENT_END,
				NULL);
	XmStringFree(compStr);
        text_w = XtVaCreateManagedWidget("copText",
					 xmLabelWidgetClass, form,
					 XmNrightAttachment, XmATTACH_FORM,
					 XmNleftAttachment,  XmATTACH_POSITION,
					 XmNleftPosition,    4,
					 NULL);
	fields[i] = text_w;
/* printf("%s  %d\n", rel->attrInfo[i].name, rel->attrInfo[i].pgType); */
        XtManageChild(form);
    }
    /* grand-total line */
    form = XtVaCreateWidget("copForm", xmFormWidgetClass, copBox, NULL);
    label = XtVaCreateManagedWidget("mathTotalLabel",
				    xmLabelGadgetClass, form,
				    XmNtopAttachment,    XmATTACH_FORM,
				    XmNbottomAttachment, XmATTACH_FORM,
				    XmNleftAttachment,   XmATTACH_FORM,
				    NULL);
    text_w = XtVaCreateManagedWidget("copText",
				     xmLabelWidgetClass, form,
				     XmNrightAttachment, XmATTACH_FORM,
				     XmNleftAttachment,  XmATTACH_WIDGET,
				     XmNleftWidget,      label,
				     XmNalignment,       XmALIGNMENT_BEGINNING,
				     NULL);
    fields[m] = text_w;
    XtManageChild(form);
    XtVaCreateManagedWidget("copSeparator", xmSeparatorWidgetClass, copBox, 
			    NULL);
    /* now for the three control boxes */
    toggleBox = XtVaCreateManagedWidget("mathToggleBox", 
					xmRowColumnWidgetClass, copBox,
					XmNorientation,  XmHORIZONTAL,
					NULL);
    frame = XtVaCreateManagedWidget("mathFrame", xmFrameWidgetClass, toggleBox,
				    NULL);
    form = XmCreateRadioBox(frame, "mathActions", NULL, 0);
    but = XtVaCreateManagedWidget("mathSum", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "Sum",
				  NULL);
    XmToggleButtonSetState(but, True, False);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathProd", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "Product",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathCount", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "Count",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathAvg", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "Average",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathSd", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "StdDev",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathMin", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "Min",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathMax", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "Max",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    XtManageChild(form);
    frame = XtVaCreateManagedWidget("mathFrame", xmFrameWidgetClass, toggleBox,
				    NULL);
    form = XmCreateRadioBox(frame, "mathAttr", NULL, 0);
    cbs->allAttrBut = but = XtVaCreateManagedWidget("mathAllAttr", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "allAttr",
				  NULL);
    XmToggleButtonSetState(but, True, False);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathKeyAttr", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "keyAttr",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    XtManageChild(form);
    frame = XtVaCreateManagedWidget("mathFrame", xmFrameWidgetClass, toggleBox,
				    NULL);
    form = XmCreateRadioBox(frame, "mathSelected", NULL, 0);
    cbs->allTuplesBut = but = XtVaCreateManagedWidget("mathAllTuples", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "allTuples",
				  NULL);
    XmToggleButtonSetState(but, True, False);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    but = XtVaCreateManagedWidget("mathSelectedTuples", 
				  xmToggleButtonGadgetClass, form,
				  XmNuserData, "selTuples",
				  NULL);
    XtAddCallback(but, XmNvalueChangedCallback, mathOk, cbs);
    XtManageChild(form);
    form = XtVaCreateWidget("copForm", xmFormWidgetClass, copBox, 
			    NULL);
    update = XtVaCreateManagedWidget("mathUpdate", 
				     xmPushButtonWidgetClass, form,
				     XmNuserData,        "noop",
				     XmNleftAttachment,  XmATTACH_FORM,
				     XmNrightAttachment, XmATTACH_POSITION,
				     XmNrightPosition,   50,
				     XmNtopAttachment,   XmATTACH_FORM,
				     XmNbottomAttachment,XmATTACH_FORM,
				     NULL);
    XtAddCallback(update, XmNactivateCallback, mathOk, cbs);
    cancel = XtVaCreateManagedWidget("copCancel", 
				     xmPushButtonWidgetClass, form,
				     XmNrightAttachment, XmATTACH_FORM,
				     XmNleftAttachment,  XmATTACH_WIDGET,
				     XmNleftWidget,      update,
				     XmNtopAttachment,   XmATTACH_FORM,
				     XmNbottomAttachment,XmATTACH_FORM,
				     NULL);
    XtAddCallback(cancel, XmNactivateCallback, mathOpsCancel, cbs);
    XtManageChild(form);
    setFormColumn(copBox, -1);
    mathOk(NULL, cbs, NULL);
    XtManageChild(copBox);
    XtPopup(sh, XtGrabNone);  
    setCursor(rel->top, None);
}





/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
void mathOpsCancel(w, mathCbs, cbs)
  Widget w;
  mathCbsStruct *mathCbs;
  XtPointer cbs;
{
    free(mathCbs->fields);
    XtDestroyWidget(mathCbs->opsSh);
    free(mathCbs);
}





/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* This function behaves as a callback of the buttons in the MATH dialog.
   Also, to avoid double coding, it does the math operations for the
   "totals" section of the report printing. The first is used when
   cbs->fields is non-null, the latter when cbs->results is non-null */
void mathOk(w, mathCbs, cbs)
  Widget w;
  mathCbsStruct *mathCbs;
  XmToggleButtonCallbackStruct *cbs;
{
    relInfo *rel = mathCbs->rel;
    int i, j, m, n;
    int type;
    Widget *fields;
    String *results;
    char *caller = "";
    PortalBuffer *portal;
    int posCount, ipos, jpos, jfirst, *posList;
    Widget list, totalW;
    double val, sum, totalSum, count, totalCount, prod, totalProd;
    double min, totalMin, max, totalMax, sqrSum, totalSqrSum, avg, stddev;
    char buf[1000];    /* will (hopefully) hold the largest result */

    if (w && cbs && !cbs->set)     /* we're interested in set events only */
	return;
    if (w)    /* we can call mathOk() manually with w==NULL */
	XtVaGetValues(w, XmNuserData, &caller, NULL);
    if (!strcmp(caller, "Sum"))             mathCbs->action = SUM;
    else if (!strcmp(caller, "Product"))    mathCbs->action = PRODUCT;
    else if (!strcmp(caller, "Count"))      mathCbs->action = COUNT;
    else if (!strcmp(caller, "Average"))    mathCbs->action = AVERAGE;
    else if (!strcmp(caller, "StdDev"))     mathCbs->action = STDDEV;
    else if (!strcmp(caller, "Min"))        mathCbs->action = MMIN;
    else if (!strcmp(caller, "Max"))        mathCbs->action = MMAX;
    else if (!strcmp(caller, "allAttr"))    mathCbs->allAttr = True;
    else if (!strcmp(caller, "keyAttr"))    mathCbs->allAttr = False;
    else if (!strcmp(caller, "allTuples"))  mathCbs->allTuples = True;
    else if (!strcmp(caller, "selTuples"))  mathCbs->allTuples = False;

    portal = PQparray(rel->portal);
    fields = mathCbs->fields;
    results = mathCbs->results;
    m = mathCbs->numFields;
    if (fields != NULL)
	totalW = fields[m];    /* must save it now, as m might change later */
    jfirst = ATTR_1ST(rel);
    n = PQntuples(portal);

    if (fields != NULL)
	for (j=ATTR_1ST(rel); j<m; j++)    /* resets the labels */
	    xs_wprintf(fields[j], "");

    list = rel->records;
    if (! mathCbs->allAttr)
    {
	list = rel->key;
	jfirst = 0;
	for (m=0; ; m++)
	    if (rel->attrInfo[m].keyList == (-1))
		break;
	if (!m)
	{
	    warn(mathCbs->opsSh, "No key attributes!");
	    XmToggleButtonSetState(mathCbs->allAttrBut, True, True);
	    return;
	}
    }
    if (! mathCbs->allTuples)
    {
	if (!XmListGetSelectedPos(list, &posList, &posCount))
	{
	    warn(mathCbs->opsSh, "No selected tuples!");	
	    XmToggleButtonSetState(mathCbs->allTuplesBut, True, True);
	    return;
	}
	n = posCount;
    }
    
    totalSum = totalSqrSum = totalCount = 0;
    totalProd = 1;
    for (j=jfirst; j<m; j++)
    {
	sum = sqrSum = count = 0;
	prod = 1;
	jpos = (mathCbs->allAttr ? j : rel->attrInfo[j].keyList);
	type = rel->attrInfo[jpos].pgType;
	if ((type>=21 && type<=23) || (type>=700 && type<=701) || 
	    mathCbs->action==COUNT || results!=NULL)
	{
	    for (i=0; i<n; i++)
	    {
		ipos = (mathCbs->allTuples ? i : posList[i]-1);
		if (PQgetvalue(portal,ipos,jpos) == NULL)
		    continue;
		sscanf(PQgetvalue(portal,ipos,jpos), "%lg", &val);
		sum += val;
		sqrSum += pow(val, 2.0);
		prod *= val;
		if (count == 0)
		    min = max = val;
		min = (val<min ? val : min);
		max = (val>max ? val : max);
		if (totalCount == 0)
		    totalMin = totalMax = val;
		totalMin = (val<totalMin ? val : totalMin);
		totalMax = (val>totalMax ? val : totalMax);
		count++;
		totalCount++;
	    }
	    totalSum += sum;
	    totalSqrSum += sqrSum;
	    totalProd *= prod;
	    if (count > 0)     /* avoid div by 0 */
	    {
		avg = sum / count;
		stddev = sqrt(sqrSum/count - pow(sum/count, 2.0));
	    }
	    if (mathCbs->action == SUM)          val = sum;
	    else if (mathCbs->action == PRODUCT) val = prod;
	    else if (mathCbs->action == COUNT)   val = count;
	    else if (mathCbs->action == MMIN)    val = min;
	    else if (mathCbs->action == MMAX)    val = max;
	    else if (mathCbs->action == AVERAGE) val = avg;
	    else if (mathCbs->action == STDDEV)  val = stddev;
	    if (count > 0)
		sprintf(buf, "%.*f", rel->res.floatPrecision, val);
	    else
		sprintf(buf, "no items");
	}
	else
	    sprintf(buf, "NaN");
	if (fields != NULL)
	    xs_wprintf(fields[jpos], buf);
	if (results != NULL  &&  count>0  && 
	    ((type>=21 && type<=23) || (type>=700 && type<=701)))
	{
	    sprintf(buf, "%.*f", rel->res.floatPrecision, sum);
	    mathResultElem(results, jpos, SUM)     = strdup(buf);
	    sprintf(buf, "%.*f", rel->res.floatPrecision, prod);
	    mathResultElem(results, jpos, PRODUCT) = strdup(buf);
	    sprintf(buf, "%.*f", rel->res.floatPrecision, avg);
	    mathResultElem(results, jpos, AVERAGE) = strdup(buf);
	    sprintf(buf, "%.*f", rel->res.floatPrecision, stddev);
	    mathResultElem(results, jpos, STDDEV)  = strdup(buf);
	    sprintf(buf, "%.*f", rel->res.floatPrecision, min);
	    mathResultElem(results, jpos, MMIN)    = strdup(buf);
	    sprintf(buf, "%.*f", rel->res.floatPrecision, max);
	    mathResultElem(results, jpos, MMAX)    = strdup(buf);
	}
	if (results != NULL)  /* because count is always printed */
	{
	    sprintf(buf, "%.*f", rel->res.floatPrecision, count);
	    mathResultElem(results, jpos, COUNT)   = strdup(buf);
	}
    }
    if (totalCount == 0)     /* avoid div by 0 */
	totalCount = (-1);
    if (mathCbs->action == SUM)          val = totalSum;
    else if (mathCbs->action == PRODUCT) val = totalProd;
    else if (mathCbs->action == COUNT)   val = totalCount;
    else if (mathCbs->action == MMIN)    val = totalMin;
    else if (mathCbs->action == MMAX)    val = totalMax;
    else if (mathCbs->action == AVERAGE) val = totalSum / totalCount;
    else if (mathCbs->action == STDDEV  &&  totalCount>0)
	val = sqrt(totalSqrSum/totalCount - pow(totalSum/totalCount, 2.0));
    if (totalCount > 0)
	sprintf(buf, "%.*f", rel->res.floatPrecision, val);
    else
	sprintf(buf, "no items");
    if (fields != NULL)
	xs_wprintf(totalW, buf);
}

