!******************************************************************************!
! 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
!   badBackgroundLay     - (OPTIONAL) Layer to use for bad background tile testing
!   useTiles             - use of tiles rather than a single image
!   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
!   testCaseInstructions - Instructions for a specific test case
!   transitions          - (OPTIONAL) Layer transitions
!   noCache              - (OPTIONAL) Turns cache on or off
!   numRetriesIfBGColor  - (OPTIONAL) Number of retries when attempting to retrieve map data from server
!   resizeWindow         - (OPTIONAL) Resize the window for map elongation testing
!
! Note:
!   Widening the graphics window for this test may cause some tests to fail,
!   such as layer transitions and brightness panning.
!
! Author:  Zachary Matthews
!
! 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"] cs:badBackgroundLay["shapePolitical"] &
            S:useTiles["TRUE"] cs:crsOverride[""] s:requestedVersion[""] s:testCaseInstructions[""] &
            S:transitions[""] Z:noCache[false] l:numRetriesIfBGCOLOR[0] Z:resizeWindow[false] Z:adjustImageOnPanning[false]
  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 DEBUG        debug        GET DEF=FALSE SDEF=TRUE
  switch DBUFFER      DBUF         GET DEF="-DBUFFER" SDEF="+DBUFFER"
  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)

  call setDatDir

  ! Create table holding LayerWMS qualifier information
  call createOptEntriesTable

  if transitions NEQS "" then
    res extReadoutValue "+SHOW|+WMS_LEVEL"
  else
    res extReadoutValue "-WMS_LEVEL"
  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"}}

  if interAct then
    pipe on
      panel/msgid=MAIN/setup/controls=gc
      plot/id=idplot ^{datDir}.world.prm{ENABLE=+BS}|{LT=WMS,IGNOREHREF=^ignoreHREF,&
                    ^{OPTENTRIES.WMS_VERSION}URL="^url",^{OPTENTRIES.CRS}&
                    ^{OPTENTRIES.CACHE_SIZE}^{OPTENTRIES.RETRIES_BG_COLOR}&
                     LAYERS="^layers",^{OPTENTRIES.LAYER_TRANSITIONS}ENABLE=+BS,USETILES=useTiles,&
                    ^{OPTENTRIES.BRIGHTNESS}^{OPTENTRIES.CONTRAST}^{OPTENTRIES.IMAGE_ADJUST_ON_PAN}^{OPTENTRIES.LEGACY_IMAGE_ADJUST}} &
                     view=LatLon options=+dbuf READOUT=+onAxis READOUTEXT=^extReadoutValue

      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}\n\n&
                        ^{testCaseInstructions}"
      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 27 /title
      if transitions neqs "" then
        invoke layerArray layers.split(",")
        res lyrBtn1 "1. ^layerArray(0)"
        res lyrBtn2 "2. ^layerArray(1)"
        res lyrBtn3 "3. ^layerArray(2)"
        res lyrBtn4 "4. ^layerArray(3)"
        gcontrol/nc=1/id=transitionzoom button ZOOMFORTRANSITION "Transition Layers" "^lyrBtn1,^lyrBtn2,^lyrBtn3,^lyrBtn4"
      endif
      if numRetriesIfBGCOLOR gt 0 then
        gcontrol label resultsLabel "Retries results" AlwaysOpen
          gcontrol prompt resultsPrompt "Retries on obtaining tiles: " "" /msg=false /edit=false 
        gcontrol label validMapLabel "Good Map Tiles" AlwaysOpen
          gcontrol button zoomGoodTileTest "" "Zoom to Good Map Tiles"
        gcontrol label badBgLbl "Bad-Background Section"
          gcontrol button toggleBadBgLay "" "Switch to Layer for Bad Background Color Test" "" 
          gcontrol button zoomSolidTileTest "" "Zoom To Solid (Bad) Tiles"
        gcontrol label badBgCoords "Coordinates for solid color (bad) tile zoom"
          gcontrol prompt bgOnlyMinLon "BG Only Min Lon: " "-82" /msg=false
          gcontrol prompt bgOnlyMaxLon "BG Only Max Lon: " "-72" /msg=false
          gcontrol prompt bgOnlyMinLat "BG Only Min Lat: " "-82" /msg=false
          gcontrol prompt bgOnlyMaxLat "BG Only Max Lat: " "-69" /msg=false

      endif
      if adjustImageOnPanning then
        gcontrol button ZOOMFORIMAGEADJUSTING "Click the button below to zoom" "Zoom to the UK" ""
      endif

      if resizeWindow then
        invoke ,, nxm.sys.test.TestPlotZoomPixelSlamTop.adjustFrameSize(reg, "{w=917,h=547}", "idplot")
      endif

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

    pipe off
  endif  ! end if interAct

  invoke ,, nxm.sys.lib.Shell.setJVMHangWorkaround(^jvmHangFix)
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
    set this.timer(0) 0
    invoke lastNumRetries reg.idplot.layers.wms.getLastNumRetries()
    set gc.resultsPrompt.value "^lastNumRetries"
    !info "Last number of retries: ^lastNumRetries"
  elseif msg.name eqs "ZOOMFORTRANSITION" then
    if msg.data eqs "^lyrBtn1" then
      message send IDPLOT  name=zoomout DATA=-1
    elseif msg.data eqs "^lyrBtn2" then
      message send IDPLOT  name=zoom DATA={X1=-93,X2=-68,Y1=24,Y2=56} 
    elseif msg.data eqs "^lyrBtn3" then
      message send IDPLOT  name=zoom DATA={X1=-78.96,X2=-75.27,Y1=36.77,Y2=41.46} 
    elseif msg.data eqs "^lyrBtn4" then
      message send IDPLOT  name=zoom DATA={X1=-77.06,X2=-76.99,Y1=38.868,Y2=38.959} 
    endif
  elseif msg.name eqs "ZOOMGOODTILETEST" then
    set gc.resultsPrompt.value "In Progress"
    message sendw IDPLOT  name=zoom DATA={X1=2,X2=31,Y1=22,Y2=65}
    set this.timer(0) 4
  elseif msg.name eqs "TOGGLEBADBGLAY" then
    if "BAD BACKGROUND COLOR" subs msg.data then
      invoke gc.toggleBadBgLay.setItem(1,"Switch to Layer for Map Test")
      invoke ,, reg.idplot.layers.wms.Layers(^{badBackgroundLay})
    else
      invoke ,, gc.toggleBadBgLay.setItem(1,"Switch to Layer for Bad Background Color Test")
      invoke ,, reg.idplot.layers.wms.Layers(^{layers})
    endif
  elseif msg.name eqs "ZOOMSOLIDTILETEST" then
    set gc.resultsPrompt.value "In Progress"
    message sendw IDPLOT  name=zoom DATA={X1=^{gc.bgOnlyMinLon.value},X2=^{gc.bgOnlyMaxLon.value},Y1=^{gc.bgOnlyMinLat.value},Y2=^{gc.bgOnlyMaxLat.value}}
    set this.timer(0) 10
  elseif msg.name eqs "ZOOMFORIMAGEADJUSTING" then
    if msg.data eqs "ZOOM TO THE UK" then
      message send IDPLOT  name=zoom DATA={X1=-6,X2=2,Y1=50,Y2=58}
    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 entries / qualifiers
!******************************************************************************!
procedure createOptEntriesTable

  TABLE OPTENTRIES CREATE {CRS="",WMS_VERSION="",LAYER_TRANSITIONS="",&
                           CACHE_SIZE="",RETRIES_BG_COLOR="",&
                           BRIGHTNESS="",CONTRAST="",IMAGE_ADJUST_ON_PAN="",LEGACY_IMAGE_ADJUST=""}
  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
  if TRANSITIONS NEQS "" THEN
    table optentries SETKEY LAYER_TRANSITIONS "TRANSITIONS=\"^{transitions}\","
  endif
  if NOCACHE then
    table optentries SETKEY CACHE_SIZE "CACHESIZE=1,"
  endif
  if NUMRETRIESIFBGCOLOR gt 0 then
    table optentries SETKEY RETRIES_BG_COLOR "NumRetriesIfBGColor=^{numRetriesIfBGColor},"
  endif
  if ADJUSTIMAGEONPANNING then
    table optentries SETKEY BRIGHTNESS "BRIGHTNESS=30,"
    table optentries SETKEY CONTRAST "CONTRAST=50,"
    table optentries SETKEY IMAGE_ADJUST_ON_PAN "ImageAdjustOnPan=true,"
    table optentries SETKEY LEGACY_IMAGE_ADJUST "LegacyImageAdjust=false,"
  endif

return
