!
! Test the plotting of files for LayerWMS to plot from Open Geospatial Consortium (OGC)
! Web Map Service (WMS) Map Server.
!
! Arguments:
!   url              - url
!   layers           - layers to display
!   numFeatures      - number of features on LatLon plot
!   useTiles         - use of tiles rather than a single image
!   numThreads       - number of download threads
!   crsOverride      - (OPTIONAL) Table that will override the table created from wms_cord_system.xml
!   requestedVersion - (OPTIONAL) Specific WMS Version request to be given priority over default
!
! Author:  J. Hallam, J. Czechowski, Neon Ngo
!
! Since 3.5.3 - this test was adjusted to use GeoServer instance on port 8800 as the default map server
!******************************************************************************!
startmacro cs:url["http://nextmidas.com:8800/geoserver/ows"] cs:layers["shapePolitical,Relief,cadrg,imint"]  &
            L:numFeatures[60] S:useTiles["TRUE"] L:numThreads[32] cs:crsOverride[""]  &
            s:requestedVersion[""]
  switch INTERACTIVE  interAct     GET DEF=TRUE  SDEF=TRUE  ! for normal interactive test(s)
  switch BASELINE     baseline     GET DEF=FALSE SDEF=TRUE  ! for defects or more obscure test case(s)
  switch COREGRAPHICS coreGraphics GET DEF=FALSE SDEF=TRUE  ! for a quick check of graphics - more extreme tests - since 3.8.1
  switch AUTO         autoTest     GET DEF=TRUE SDEF=TRUE
  ! NTN: switches to help test Bug 2059 Features (-BS) Flashes on PLOT (Map w/ +BS) over X11
  switch INTERVAL     interval     GET DEF=0.5
  switch HOLDREFRESH  holdRefresh  GET DEF=FALSE SDEF=TRUE
  switch FEATSONBS    featsOnBS    GET DEF=OFF SDEF=ON
  switch DBUFFER      DBUF         GET DEF="-DBUFFER" SDEF="+DBUFFER"
  switch SYMBOL       featsymbol   GET DEF="Star"
  switch PLOTPOLL     poll         GET DEF=1/80
  switch NOCONFIGMENU noconfigMenu GET DEF=FALSE SDEF=TRUE
  switch IGNOREHREF   ignoreHREF   GET DEF=FALSE SDEF=TRUE ! Ignore GetCapabilities HREF and use original URL

  invoke z:jvmHangFix nxm.sys.lib.Shell.getJVMHangWorkaround()
  res z:mytrue true
  invoke ,, nxm.sys.lib.Shell.setJVMHangWorkaround(^mytrue)

  if interAct or coreGraphics then
    call setDatDir

    invoke CHANGED_BY_POLL nxm.sys.libg.GValue.CHANGED_BY_POLL
    set noAuto TEST(autoTest,isFalse)
    if featsOnBS then
      set featEnableOptions "+BS"
    else
      set featEnableOptions "-BS"
    endif

    call createOptEntriesTable

    ! go ahead and turn this one off too if say no features
    IF numFeatures EQ 0 THEN
      res Z:noAuto true
      res Z:autoTest false
    ENDIF

    set Z:configMenu TEST(noConfigMenu,isFalse) 

    ! unused example of alternate coordinate reference system table
    table EPSG4326TBL CREATE {CRS_1={NAME=EPSG:4326,X="latitude",Y="longitude",Z="none",ALLOW="true"}}

    ! can add in TRANSITIONS="500,1.5e3,1e8", after LAYERS for testing transitions

    set featureTab {NAME="FEAT",TYPE="|SYMBOL|",X=0,Y=0,DX=0,DY=0,COLOR="RED",ENABLE=featEnableOptions,&
                    LINE={SYMBOL="DIAMOND",SYMBOLFILL="TRUE",SYMBOLSIZE=10}}
    set featureColorList "RED,GREEN,BLUE,YELLOW"
    res z:adjust true
    res z:legacyImageAdjust false
    res l:bright 30
    res l:contrast 50

    pipe on
      panel/msgid=MAIN/setup/controls=gc
      plot/id=idplot ^{datDir}.world.prm{ENABLE=+BS}|{LT=WMS,IGNOREHREF=true,^{OPTENTRIES.WMS_VERSION}URL="^url",^{OPTENTRIES.CRS}&
                     LAYERS="^layers",ENABLE=+BS,USETILES=useTiles,BRIGHTNESS=^bright,CONTRAST=^contrast,ImageAdjustOnPan=^adjust,&
                     LegacyImageAdjust=^legacyImageAdjust,DOWNLOADTHREADS=numThreads,NumRetriesIfBGColor=3} view=LatLon options=+dbuf READOUTEXT=+Show|+WMS_level READOUT=+onAxis

      IF numFeatures NEQ 0 THEN
        feature label=ffeat table=^{featureTab} plot=idplot
      ENDIF

      ! adding n features to PLOT for testing Bug 2059
      set slat   90  ! starting (seed) latitude (y pos)
      set slon  180  ! starting (seed) longitude (x pos)
      ! loop to draw specified number of features
      do ii 1 numFeatures
        res label "FEAT^{ii}"
        calc y slat ii 1 - 10 * -
        ! note, a prime mulitpiler (e.g. 17) works best for x here
        calc x slon ii 1 - 17 * -
        ! reset slat when y gets out of range
        if y le -90 then
          calc slat slat 180 +
        endif
        ! reset x and slon when x is out of range
        if x le -180 then
          calc x x 360 +
          calc slon slon 360 +
        endif
        if /debug then  say " ii=^ii  lab=^label x=^x y=^y  slon=^slon"
        feature label=^{label} table=^{featureTab}{NAME=^label,x=^x,y=^y,COLOR="WHITE",SYMBOL=featsymbol} plot=idplot
      enddo

      gcontrol label macro "MACRO"
      gcontrol menu    main "Exit with Status = " "PASS,FAIL" /tleft
      set gc.main.itemColors {PASS=GREEN,FAIL=RED}

      set baselineInstructions ""
      if baseline OR configMenu then set baselineInstructions "Move the config menu out of the way, but do not close it. "
      set instructions "^{baselineInstructions}&
                        Maps should be shown in background. You should see charts and imagery where they exist. &
                        You may or may not notice the feature flashing when redrawn. &
                        Put the feature in BACKING STORE then move the mouse over the map. &
                        The cursor should NOT change back and forth between WAIT and DEFAULT cursors. &
                        Before the DR fix, the cursor would periodically change. &
                        Zoom in and out to make sure the cursor is WAIT when downloading and returns &
                        to DEFAULT when done."
      if baseline then set instructions "^{instructions} The WMS Layer config menu should disappear when you &
                        close the plot (in 2.6.0 the config menu remained)."
      gcontrol text    idtext "Instructions" "^instructions" 24 16 /title
      gcontrol label tests "Options" AlwaysOpen

      gcontrol dval   featurePosX     "Position-X"                  featureTab.X     -180 180 15 /edit=^noAuto /mon=ffeat.x
      gcontrol dval   featureSizeDX   "Size-DX"                     featureTab.DX       0  30  5 /edit=^noAuto /mon=ffeat.dx
      gcontrol dval   featurePosY     "Position-Y"                  featureTab.Y      -90  90 15 /edit=^noAuto /mon=ffeat.y
      gcontrol dval   featureSizeDY   "Size-DY"                     featureTab.DY       0  30  5 /edit=^noAuto /mon=ffeat.dy
      gcontrol choice featureColor    "Color"      featureColorList featureTab.color
      ! gcontrol button resizePlot      ""           "ResizePlot"  ! JWB: no explanation why this was here so disabled

      gcontrol choice bsMap  "Use BackingStore for Map" "On,Off" "On"
      gcontrol choice bsWMS  "Use BackingStore for WMS" "On,Off" "On"
      gcontrol choice bsFea  "Use BackingStore for Fea" "On,Off" featsOnBS
      set gc.bsMap.itemColors {On=GREEN,Off=RED}
      set gc.bsWMS.itemColors {On=GREEN,Off=RED}
      set gc.bsFea.itemColors {On=GREEN,Off=RED}

      gcontrol/nc=2 button zooms "DIFFERENT ZOOMS (performance evaluation only)" &
                  "US,SOUTH AMERICA,AUSTRALIA,AFRICA,UK,ITALY,GERMANY,NORTH PACIFIC,INDIAN OCEAN" ""

      if baseline OR configMenu then
        invoke ,, reg.idplot.layers.wms.configure
      endif

      if autoTest isTrue then
         set reg.panel.timer(0) interval
      endif
    pipe off
  endif  ! end if interAct

  invoke ,, nxm.sys.lib.Shell.setJVMHangWorkaround(^jvmHangFix)

  ! Additional interactive tests, only run with /BASELINE
  if interAct and baseline then
    %test_plot_layerwms_range       ! Bug 1349 Bug 2880
    %test_plot_layerwms_toggle      ! Bug 1621
    !%test_plot_layerwms_loose_spec ! Since 3.5.3 & change to geoserver not applicable
    %test_plot_layerwms_pan         ! Since 3.7.2 for NXM-3034

  ! If COREGRAPHICS run a short list of extreme tests that tend to be the ones to show graphical issues
  elseif coreGraphics then
    %test_plot_layerwms_pan         ! Since 3.7.2 for NXM-3034
  endif
endmacro

!******************************************************************************!
procedure processMessage m:msg
  !say "Got Message: name=^msg.name info=^msg.info data=^msg.data"

  if msg.name eqs "MAIN" then
    assert/text="^reg.main.name: Interactive tests" msg.data eqss "PASS"
    pipe stop

  elseif msg.name eqs "TIMER" then
    calc newX ffeat.x 15 +
    if newX gt 180 then
      calc newX newX 360 -
    endif
    set ffeat.x newX

    ! loop to update x (longitude) location of the features for Bug 2059
    if holdRefresh then set reg.idplot.holdRefresh FEATURES
    do ii 1 numFeatures
      res label "FEAT^{ii}"
      calc newX ^{label}.x 15 +
      if newX gt 180 then
        calc newX newX 360 -
      endif
      set ^{label}.x newX
    enddo
    if holdrefresh then set reg.idplot.holdRefresh NONE

  elseif msg.name eqs "RESIZEPLOT" then
    invoke ,, reg.idplot.resize()

  elseif msg.name eqss "BSMAP" then
    if msg.data isTrue then
      set reg.idplot.layers.world.enable +BS
    else
      set reg.idplot.layers.world.enable -BS
    endif

  elseif msg.name eqss "BSWMS" then
    if msg.data isTrue then
      set reg.idplot.layers.wms.enable +BS
    else
      set reg.idplot.layers.wms.enable -BS
    endif

  elseif msg.name eqss "BSFEA" then

    if msg.data isTrue then
      set enableMask "+BS"
    else
      set enableMask "-BS"
    endif

    set reg.idplot.features.feat.enable enableMask
    do ii 1 numFeatures
      res label "FEAT^{ii}"
      set ^{label}.enable enableMask
    enddo

  elseif msg.name eqss "FEATURE" then
    !info "msg.data '^msg.data', flags value ^gc.featureType.value"

    if msg.info eq CHANGED_BY_POLL then
      ! ignore changes caused by polling
    elseif msg.name eqss "FEATURESIZEDY" then
      set ffeat.dy ^msg.data
    elseif msg.name eqss "FEATURESIZEDX" then
      set ffeat.dx ^msg.data
    elseif msg.name eqss "FEATUREPOSY" then
      set ffeat.y ^msg.data
    elseif msg.name eqss "FEATUREPOSX" then
      set ffeat.x ^msg.data
    elseif msg.name eqs "FEATURECOLOR" then
      set ffeat.color ^msg.data
    else
      warning "^reg.main.name: Do not know ^msg.data feature"
    endif

  elseif msg.name eqss "ZOOMS" then
    if msg.data eqss US  then
      message send IDPLOT  name=zoom DATA={X1=-124,X2=-72,Y1=8,Y2=65}
    elseif msg.data eqss "SOUTH AMERICA" then
      message send IDPLOT  name=zoom DATA={X1=-90,X2=-20,Y1=-60,Y2=12}
    elseif msg.data eqss "AUSTRALIA" then
      message send IDPLOT  name=zoom DATA={X1=110,X2=160,Y1=-50,Y2=0}
    elseif msg.data eqss "AFRICA" then
      message send IDPLOT  name=zoom DATA={X1=-20,X2=55,Y1=-40,Y2=35}
    elseif msg.data eqss "GERMANY" then
      message send IDPLOT  name=zoom DATA={X1=6,X2=16,Y1=44,Y2=55}
    elseif msg.data eqss "ITALY" then
      message send IDPLOT  name=zoom DATA={X1=6,X2=18,Y1=35,Y2=48}
    elseif msg.data eqss "UK" then
      message send IDPLOT  name=zoom DATA={X1=-6,X2=2,Y1=50,Y2=58}
    elseif msg.data eqss "NORTH PACIFIC" then
      message send IDPLOT  name=zoom DATA={X1=-157,X2=-128,Y1=10,Y2=50}
    elseif msg.data eqss "INDIAN OCEAN" then
      message send IDPLOT  name=zoom DATA={X1=70,X2=95,Y1=-35,Y2=5}
    endif
  else
    say "Unhandled message name: ^msg.name from fid: ^msg.fid dats: ^msg.data"
  endif
return

!******************************************************************************!
! Set the dat directory
!******************************************************************************!
procedure setDatDir
  invoke nxmMajor env.nmversion.subString(0,1)
  invoke major java.lang.Integer.valueOf(nxmMajor)
  if major GE 4 then
    invoke s:datDir           nxm.sys.test.DatLocator.getDatDirLocation()
    invoke s:datDirSlash      nxm.sys.test.DatLocator.getDatDirSlashLocation()
    invoke z:sysDatFull       nxm.sys.test.DatLocator.sysDatFull()
    invoke z:sysTestDatExists nxm.sys.test.DatLocator.sysTestDatExists()
  else
    set s:datDir           "nxm.sys.dat"
    set s:datDirSlash      "nxm/sys/dat"
    set z:sysDatFull       true
    set z:sysTestDatExists false
  endif
return

!******************************************************************************!
! Create Table holding optional LayerWMS LAYER entries
!******************************************************************************!
procedure createOptEntriesTable

  TABLE OPTENTRIES CREATE {CRS="",WMS_VERSION=""}
  if CRSOVERRIDE STARTS "{" THEN
    table optentries SETKEY CRS "CoordRefSystems=^{crsOverride},"
  elseif CRSOVERRIDE NEQS "" THEN
    ! NXM-3743 support adding CRS entries by name
    table optentries SETKEY CRS "ByNameCRSs=^{crsOverride},"
  endif
  if REQUESTEDVERSION NEQS "" THEN
    table optentries SETKEY WMS_VERSION "RequestedVersion=^{requestedVersion},"
  endif

return
