/*------------------------------------------------------------------------
    File        : spreadsheet_demo.p
    Purpose     : FWD User Meeting demo (#12087, topic 15): the SPREADSHEET
                  widget, the FWD replacement of the Formula One spreadsheet
                  OCX, running in the web client.

    Notes       : The 4GL code uses the OCX API unchanged (chCtrlFrame:F1Book,
                  mapped to the FWD widget by spreadsheet_demo.p.ext-hints):
                  1. Builds a quarterly sales workbook: title, a colored
                     header, number formats, SUM formulas for the totals and a
                     share column, a second sheet with notes.
                  2. Reacts to the user: the EndEdit event validates every
                     edit (a quarter cell takes numbers only) and SelChange
                     reads the recalculated totals back into 4GL.
                  3. Changes the sheet from 4GL: "+10% for Q4" updates the
                     numbers and the formulas follow; "Highlight Best" finds
                     the best product and marks its row.
  ----------------------------------------------------------------------*/

&SCOPED-DEFINE F1 chCtrlFrame:F1Book

/* workbook layout */
&SCOPED-DEFINE ROW-TITLE  1
&SCOPED-DEFINE ROW-HEAD   3
&SCOPED-DEFINE ROW-FIRST  4
&SCOPED-DEFINE ROW-LAST   9
&SCOPED-DEFINE ROW-TOTAL  10
&SCOPED-DEFINE COL-TOTAL  6
&SCOPED-DEFINE COL-SHARE  7

DEFINE VARIABLE CtrlFrame   AS WIDGET-HANDLE NO-UNDO.
DEFINE VARIABLE chCtrlFrame AS COM-HANDLE    NO-UNDO.
DEFINE VARIABLE iBestRow    AS INTEGER       NO-UNDO.
DEFINE VARIABLE cOldEntry   AS CHARACTER     NO-UNDO.  /* the active cell's content before an edit */
DEFINE VARIABLE iFixRow     AS INTEGER       NO-UNDO.  /* a rejected edit to undo, see SelChange */
DEFINE VARIABLE iFixCol     AS INTEGER       NO-UNDO.
DEFINE VARIABLE cFixEntry   AS CHARACTER     NO-UNDO.

DEFINE VARIABLE dGrand  AS DECIMAL   NO-UNDO FORMAT ">>>,>>>,>>9"  LABEL "Grand total".
DEFINE VARIABLE cBest   AS CHARACTER NO-UNDO FORMAT "x(20)"        LABEL "Best product".
DEFINE VARIABLE dBest   AS DECIMAL   NO-UNDO FORMAT ">>>,>>>,>>9"  LABEL "Its total".
DEFINE VARIABLE cStatus AS CHARACTER NO-UNDO FORMAT "x(90)"        LABEL "Status"
   INITIAL "Edit a quarter cell, or use the buttons".
DEFINE VARIABLE cLog    AS CHARACTER NO-UNDO
   VIEW-AS EDITOR SCROLLBAR-VERTICAL SIZE-PIXELS 418 BY 150.

DEFINE BUTTON btnReload LABEL "Reload"         SIZE-PIXELS 100 BY 26.
DEFINE BUTTON btnRaise  LABEL "+10% for Q4"    SIZE-PIXELS 100 BY 26.
DEFINE BUTTON btnBest   LABEL "Highlight Best" SIZE-PIXELS 110 BY 26.
DEFINE BUTTON btnExit   LABEL "Exit"           SIZE-PIXELS 80  BY 26.

DEFINE FRAME fMain
   btnReload AT X 12  Y 340
   btnRaise  AT X 120 Y 340
   btnBest   AT X 228 Y 340
   btnExit   AT X 808 Y 340
   "Read back by 4GL code:" AT X 12  Y 380
   dGrand    AT X 110 Y 404
   cBest     AT X 110 Y 428
   dBest     AT X 110 Y 452
   "Sheet events:"          AT X 470 Y 380
   cLog      AT X 470 Y 398 NO-LABEL
   cStatus   AT X 60  Y 560
   WITH SIDE-LABELS SIZE-PIXELS 900 BY 590 THREE-D NO-BOX.

ASSIGN
   CURRENT-WINDOW:TITLE         = "Quarterly Sales"
   CURRENT-WINDOW:WIDTH-PIXELS  = 900
   CURRENT-WINDOW:HEIGHT-PIXELS = 590.

ON CHOOSE OF btnReload IN FRAME fMain DO:
   RUN logEvent("Window: Reload").
   RUN buildSheet.
END.

ON CHOOSE OF btnRaise IN FRAME fMain DO:
   RUN logEvent("Window: +10% for Q4").
   RUN raiseQ4.
END.

ON CHOOSE OF btnBest IN FRAME fMain DO:
   RUN logEvent("Window: Highlight Best").
   RUN highlightBest.
END.

ON CHOOSE OF btnExit IN FRAME fMain
   APPLY "CLOSE" TO THIS-PROCEDURE.

CREATE CONTROL-FRAME CtrlFrame
   ASSIGN FRAME         = FRAME fMain:HANDLE
          X             = 12
          Y             = 12
          WIDTH-PIXELS  = 876
          HEIGHT-PIXELS = 316
          TAB-STOP      = TRUE
          HIDDEN        = TRUE
          SENSITIVE     = TRUE.
/* FWD takes the OCX name of the event procedures (sheet.F1Book.EndEdit) from the NAME */
CtrlFrame:NAME = "sheet.F1Book".
chCtrlFrame = CtrlFrame:COM-HANDLE.
{&F1}:LoadControls("", "spreadsheet").

VIEW FRAME fMain.
DISPLAY cStatus WITH FRAME fMain.
ENABLE btnReload btnRaise btnBest btnExit cLog WITH FRAME fMain.
cLog:READ-ONLY IN FRAME fMain = TRUE.
CtrlFrame:HIDDEN = FALSE.

RUN buildSheet.

WAIT-FOR CLOSE OF THIS-PROCEDURE.

IF VALID-HANDLE(CtrlFrame) THEN
   DELETE WIDGET CtrlFrame.

/* ----------------------------------------------------------------------
   window helpers
   ---------------------------------------------------------------------- */
PROCEDURE setStatus:
   DEFINE INPUT PARAMETER pcText AS CHARACTER NO-UNDO.

   cStatus = pcText.
   DISPLAY cStatus WITH FRAME fMain.
END PROCEDURE.

PROCEDURE logEvent:
   DEFINE INPUT PARAMETER pcText AS CHARACTER NO-UNDO.

   cLog = cLog + (IF cLog = "" THEN "" ELSE CHR(10)) + STRING(TIME, "HH:MM:SS") + "  " + pcText.
   DISPLAY cLog WITH FRAME fMain.
   cLog:CURSOR-OFFSET IN FRAME fMain = LENGTH(cLog) + 1.
END PROCEDURE.

FUNCTION cellName RETURNS CHARACTER (INPUT piRow AS INTEGER, INPUT piCol AS INTEGER):
   RETURN CHR(64 + piCol) + STRING(piRow).
END FUNCTION.

/* ----------------------------------------------------------------------
   the workbook
   ---------------------------------------------------------------------- */
PROCEDURE buildSheet:
   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.
   DEFINE VARIABLE iCol AS INTEGER NO-UNDO.

   /* product, Q1, Q2, Q3, Q4 */
   DEFINE VARIABLE cData AS CHARACTER NO-UNDO EXTENT 6 INITIAL [
      "Garden Tools,42500,51200,63800,38900",
      "Seeds and Bulbs,61800,48300,22100,30400",
      "Planters,18400,24600,29900,21700",
      "Irrigation,12900,33500,47200,15800",
      "Outdoor Lighting,15600,14200,19800,36500",
      "Garden Furniture,22300,41700,52600,17900" ].

   {&F1}:StartBatch().
   {&F1}:ClearRange(1, 1, 30, 10, 3).
   iBestRow = 0.

   /* title */
   {&F1}:TextRC({&ROW-TITLE}, 1) = "Quarterly Sales 2026 - Northwind Garden Supplies".
   RUN styleRange({&ROW-TITLE}, 1, {&ROW-TITLE}, 1, 14, RGB-VALUE(10, 129, 209), -1, "").

   /* header */
   {&F1}:TextRC({&ROW-HEAD}, 1) = "Product".
   DO iCol = 2 TO 5:
      {&F1}:TextRC({&ROW-HEAD}, iCol) = "Q" + STRING(iCol - 1).
   END.
   {&F1}:TextRC({&ROW-HEAD}, {&COL-TOTAL}) = "Total".
   {&F1}:TextRC({&ROW-HEAD}, {&COL-SHARE}) = "Share".
   RUN styleRange({&ROW-HEAD}, 1, {&ROW-HEAD}, {&COL-SHARE}, 10, RGB-VALUE(255, 255, 255),
                  RGB-VALUE(51, 49, 49), "").

   /* data rows: numbers from 4GL, totals and shares as formulas */
   DO iRow = {&ROW-FIRST} TO {&ROW-LAST}:
      {&F1}:TextRC(iRow, 1) = ENTRY(1, cData[iRow - {&ROW-FIRST} + 1]).
      DO iCol = 2 TO 5:
         {&F1}:NumberRC(iRow, iCol) = DECIMAL(ENTRY(iCol, cData[iRow - {&ROW-FIRST} + 1])).
      END.
      {&F1}:FormulaRC(iRow, {&COL-TOTAL}) = "SUM(B" + STRING(iRow) + ":E" + STRING(iRow) + ")".
      {&F1}:FormulaRC(iRow, {&COL-SHARE}) = "F" + STRING(iRow) + "/$F$" + STRING({&ROW-TOTAL}).
   END.

   /* total row */
   {&F1}:TextRC({&ROW-TOTAL}, 1) = "Total".
   DO iCol = 2 TO {&COL-SHARE}:
      {&F1}:FormulaRC({&ROW-TOTAL}, iCol) = "SUM(" + cellName({&ROW-FIRST}, iCol) + ":"
                                            + cellName({&ROW-LAST}, iCol) + ")".
   END.

   /* data and total rows, one style per range (see styleRange) */
   DO iRow = {&ROW-FIRST} TO {&ROW-LAST}:
      RUN styleDataRow(iRow, -1).
   END.
   RUN styleTotalRow.

   {&F1}:SetColWidthAuto({&ROW-HEAD}, 2, {&ROW-TOTAL}, {&COL-SHARE}, FALSE).
   /* the product names: 18 characters, in 1/256 of a character as in Formula One */
   {&F1}:ColWidth(1) = 18 * 256.
   {&F1}:SheetName(1) = "Sales 2026".
   /* every other cell is locked: totals and shares are formulas */
   {&F1}:EnableProtection = TRUE.
   /* A1 active, so the sheet shows from the title on */
   {&F1}:SetActiveCell(1, 1).
   {&F1}:EndBatch().

   RUN readBack.
   RUN logEvent("Workbook built by 4GL: " + STRING({&ROW-LAST} - {&ROW-FIRST} + 1) + " products, "
                + "formulas for totals and shares").
   RUN setStatus("Edit a quarter cell, or use the buttons").
END PROCEDURE.

/* Style a range of cells in one go: bold font of the given size and color, an optional solid fill and
   an optional number format.  FWD applies each call with the style of the range's top-left cell, so a
   range must not mix cells of different styles. */
PROCEDURE styleRange:
   DEFINE INPUT PARAMETER piRow1   AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piCol1   AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piRow2   AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piCol2   AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piSize   AS INTEGER   NO-UNDO.  /* 0: keep the font */
   DEFINE INPUT PARAMETER piColor  AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piFill   AS INTEGER   NO-UNDO.  /* -1: no fill */
   DEFINE INPUT PARAMETER pcFormat AS CHARACTER NO-UNDO.  /* "": keep the format */

   {&F1}:SetSelection(piRow1, piCol1, piRow2, piCol2).
   IF piSize > 0 THEN
      {&F1}:SetFont("Arial", piSize, TRUE, FALSE, FALSE, FALSE, piColor, FALSE, FALSE).
   IF piFill >= 0 THEN
      {&F1}:SetPattern(1, piFill, piFill).
   ELSE
      {&F1}:SetPattern(0, RGB-VALUE(255, 255, 255), RGB-VALUE(255, 255, 255)).
   IF pcFormat <> "" THEN
      {&F1}:NumberFormat = pcFormat.
END PROCEDURE.

/* A data row: plain product and quarters, bold blue total and share; piFill -1 for no highlight. */
PROCEDURE styleDataRow:
   DEFINE INPUT PARAMETER piRow  AS INTEGER NO-UNDO.
   DEFINE INPUT PARAMETER piFill AS INTEGER NO-UNDO.

   RUN styleRange(piRow, 1, piRow, 1, 0, 0, piFill, "").
   RUN styleRange(piRow, 2, piRow, 5, 0, 0, piFill, "#,##0").
   /* the quarter values are the only cells the user can edit */
   {&F1}:SetProtection(FALSE, FALSE).
   RUN styleRange(piRow, {&COL-TOTAL}, piRow, {&COL-TOTAL}, 10, RGB-VALUE(10, 129, 209), piFill, "#,##0").
   RUN styleRange(piRow, {&COL-SHARE}, piRow, {&COL-SHARE}, 10, RGB-VALUE(10, 129, 209), piFill, "0.0%").
END PROCEDURE.

PROCEDURE styleTotalRow:
   DEFINE VARIABLE iGrey AS INTEGER NO-UNDO.

   iGrey = RGB-VALUE(219, 221, 220).
   RUN styleRange({&ROW-TOTAL}, 1, {&ROW-TOTAL}, 1, 10, RGB-VALUE(0, 0, 0), iGrey, "").
   RUN styleRange({&ROW-TOTAL}, 2, {&ROW-TOTAL}, 5, 10, RGB-VALUE(0, 0, 0), iGrey, "#,##0").
   RUN styleRange({&ROW-TOTAL}, {&COL-TOTAL}, {&ROW-TOTAL}, {&COL-TOTAL}, 10, RGB-VALUE(10, 129, 209),
                  iGrey, "#,##0").
   RUN styleRange({&ROW-TOTAL}, {&COL-SHARE}, {&ROW-TOTAL}, {&COL-SHARE}, 10, RGB-VALUE(10, 129, 209),
                  iGrey, "0.0%").
END PROCEDURE.

/* Read the recalculated results back from the sheet into 4GL. */
PROCEDURE readBack:
   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.
   DEFINE VARIABLE dVal AS DECIMAL NO-UNDO.

   ASSIGN
      dGrand = {&F1}:NumberRC({&ROW-TOTAL}, {&COL-TOTAL})
      dBest  = 0
      cBest  = "".
   DO iRow = {&ROW-FIRST} TO {&ROW-LAST}:
      dVal = {&F1}:NumberRC(iRow, {&COL-TOTAL}).
      IF dVal > dBest THEN
         ASSIGN
            dBest    = dVal
            cBest    = {&F1}:TextRC(iRow, 1)
            iBestRow = iRow.
   END.
   DISPLAY dGrand cBest dBest WITH FRAME fMain.
END PROCEDURE.

/* 4GL changes the data: Q4 up by 10 percent; the totals and shares follow by themselves. */
PROCEDURE raiseQ4:
   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.

   {&F1}:StartBatch().
   DO iRow = {&ROW-FIRST} TO {&ROW-LAST}:
      {&F1}:NumberRC(iRow, 5) = ROUND({&F1}:NumberRC(iRow, 5) * 1.1, 0).
   END.
   {&F1}:EndBatch().
   RUN readBack.
   RUN logEvent("Q4 raised by 10%, grand total now " + TRIM(STRING(dGrand, ">>>,>>>,>>9"))).
   RUN setStatus("Q4 raised by 10% in 4GL; the formulas updated the totals").
END PROCEDURE.

/* 4GL formats the sheet: the best product's row gets a highlight. */
PROCEDURE highlightBest:
   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.

   RUN readBack.
   {&F1}:StartBatch().
   /* clear an earlier highlight, then mark the best row */
   DO iRow = {&ROW-FIRST} TO {&ROW-LAST}:
      RUN styleDataRow(iRow, IF iRow = iBestRow THEN RGB-VALUE(0, 242, 255) ELSE -1).
   END.
   /* styling leaves the last styled cell selected: select the best product's name instead */
   {&F1}:SetSelection(iBestRow, 1, iBestRow, 1).
   {&F1}:EndBatch().
   RUN logEvent("Best product: " + cBest + ", row " + STRING(iBestRow) + " highlighted").
   RUN setStatus("Best product " + cBest + " (" + TRIM(STRING(dBest, ">>>,>>>,>>9")) + ") highlighted by 4GL").
END PROCEDURE.

/* ----------------------------------------------------------------------
   sheet events (OCX event procedures: NAME of the control frame + event)
   ---------------------------------------------------------------------- */

/* Every edit of a quarter cell: amounts only.  An invalid entry is undone: SelChange, which follows
   when the edit is committed, writes the cell's previous content back. */
PROCEDURE sheet.F1Book.EndEdit:
   DEFINE INPUT-OUTPUT PARAMETER p-EditString AS CHARACTER NO-UNDO.
   DEFINE INPUT-OUTPUT PARAMETER p-Cancel     AS INTEGER   NO-UNDO.

   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.
   DEFINE VARIABLE iCol AS INTEGER NO-UNDO.
   DEFINE VARIABLE dVal AS DECIMAL NO-UNDO.

   {&F1}:GetActiveCell(OUTPUT iRow, OUTPUT iCol).

   dVal = DECIMAL(REPLACE(p-EditString, ",", "")) NO-ERROR.
   IF ERROR-STATUS:ERROR OR dVal < 0 OR TRIM(p-EditString) = "" THEN
   DO:
      RUN logEvent("EndEdit " + cellName(iRow, iCol) + " [" + p-EditString + "] rejected, kept "
                   + cOldEntry).
      ASSIGN
         iFixRow   = iRow
         iFixCol   = iCol
         cFixEntry = cOldEntry.
      RETURN.
   END.

   RUN logEvent("EndEdit " + cellName(iRow, iCol) + " [" + p-EditString + "] accepted").
END PROCEDURE.

/* A new active cell (also after an edit, when Enter moves down): remember its content and read the
   recalculated totals back. */
PROCEDURE sheet.F1Book.SelChange:
   DEFINE VARIABLE dOld AS DECIMAL NO-UNDO.
   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.
   DEFINE VARIABLE iCol AS INTEGER NO-UNDO.

   /* undo a rejected edit, now that it is committed */
   IF iFixRow > 0 THEN
   DO:
      {&F1}:EntryRC(iFixRow, iFixCol) = cFixEntry.
      RUN logEvent("4GL restored " + cellName(iFixRow, iFixCol) + " to " + cFixEntry).
      RUN setStatus("Not an amount: " + cellName(iFixRow, iFixCol) + " keeps " + cFixEntry).
      iFixRow = 0.
      /* the totals are those from before the rejected edit: nothing to read back */
      {&F1}:GetActiveCell(OUTPUT iRow, OUTPUT iCol).
      cOldEntry = {&F1}:EntryRC(iRow, iCol).
      RETURN.
   END.

   /* remember the content of the new active cell, for EndEdit */
   {&F1}:GetActiveCell(OUTPUT iRow, OUTPUT iCol).
   cOldEntry = {&F1}:EntryRC(iRow, iCol).

   dOld = dGrand.
   RUN readBack.
   IF dGrand <> dOld THEN
   DO:
      RUN logEvent("SelChange: grand total " + TRIM(STRING(dOld, ">>>,>>>,>>9")) + " -> "
                   + TRIM(STRING(dGrand, ">>>,>>>,>>9"))).
      RUN setStatus("The sheet recalculated; 4GL read the new totals").
   END.
END PROCEDURE.
