!******************************************************************************!
! Configurable demo of NextMidas Map Capabilities
!
! Arguments:
! user_kml       allows demoing of operational KML files
! wms_config_tbl allows demoing of operational WMS
! user_t5        allows demoing of operational T5 files
!
! @since    4.1.1
! @author:  Jeanette McCall
!******************************************************************************!
startmacro cs:user_kml t:wms_config_tbl cs:user_t5
  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)

  call basicSetup
  call wmsSetup

  if interAct then
    set instructions "Demo of some of our map types and capabilities\n\n&
                      - Some types are: Midas BLUE, WMS, KML, Shape, ...\n&
                      - Shows pipe opening, closing, hiding, showing, clearing\n&
                      - Track fade and clustering options\n&
                      - Point selection and popup information\n&
                      - Adding on a Feature"

    set ellipselayertrajectory "LT=T5,TimeOrder=False,Group=drawablegrp,NAME=trajectory,ColorFade=TRUE,ColorFadeFactor=1,Field=Symbols,AutoselectEnable=CLICK,AutoSelectMode=PIXEL,SELECTCOLOR=BLUE,SELECTMESSAGES=TRUE"
    set ellipselayerflight "LT=T5,TimeOrder=False,Group=drawablegrp,NAME=flight,ColorFade=TRUE,ColorFadeFactor=1,Field=Symbols,AutoselectEnable=CLICK,AutoSelectMode=PIXEL,SELECTCOLOR=BLUE,SELECTMESSAGES=TRUE"

    invoke booleanfalse java.lang.Boolean.valueOf("false")
    invoke booleantrue java.lang.Boolean.valueOf("true")
    invoke origT5Setting   nxm.sys.libg.LayerT5.getAutoAdjustLineColor()
    invoke origPolySetting nxm.sys.libg.LayerPoly.getAutoAdjustLineColor()
    invoke ,, nxm.sys.libg.LayerT5.setAutoAdjustLineColor(^booleantrue)
    invoke ,, nxm.sys.libg.LayerPoly.setAutoAdjustLineColor(^booleantrue)

    pipe on
      panel/msgid=MAIN/setup/controls=gc
      gcontrol label macro "Test MACRO"
      gcontrol menu  main "Click EXIT to close =" "EXIT" TABLE={ItemColors={EXIT="YELLOW"}} /tleft
      gcontrol text  idtext "Instructions" instructions 24 10 /title /wtheme={CWFG=WHITE}

      plot/id=timepipe/msgid=main world|{LT="Drawable",name=drawablegrp,listlayers=true} readoutExt=+SHOW|+POINTS &
               readout=+OnAxis|+AlwaysDeltas view=latloncontinuous Y1=-90 Y2=90

      gcontrol button MAPS "Selections" "Shape,Sample KML,Operational KML,T5 FLIGHT,T5 TRAJECTORY,Operational T5,Operational WMS" "" /nc=3 /toggle /chkbox /wtheme={CWFG=WHITE}
      gcontrol line spaceFile "SomeWorthlessText" "BLUE" 7 ,, "CENTER"    ! Blue spacer
      gcontrol label fileSection "File / Pipe Control Section"
      gcontrol file shapefileselection "Shape File Selection" &
          ^shapefile "*.shp" "1|CWD|DAT" 60 10 /FLAGS="EXT" /wtheme={CWFG=WHITE}
      gcontrol button clearLayers "Clear Layers" "^flight,^trajectory" "" /wtheme={CWFG=WHITE}
      gcontrol/nc=1 button cluster "Turn clustering off/on" "^clusterDecluster" /wtheme={CWFG=WHITE}

      gcontrol line spaceFeat "SomeWorthlessText" "BLUE" 7 ,, "CENTER"    ! Blue spacer
      gcontrol label featSection "Feature Control Section"
      gcontrol prompt featTextPrompt "Update Feature Text here:" "" /wtheme={CWFG=WHITE}
      gcontrol text featureText "Feature Text" defaultFeatureText 24 4 /title /wtheme={CWFG=WHITE}
      gcontrol button featureButt "Add IconSymbol Feature with Text location:" "default,RTAG,TTAG,LTAG,BTAG,DTAG,CUSTOMTAG,none" "none" /wtheme={CWFG=WHITE}
      gcontrol button customTagRef "Custom Tag Reference Location" "TR,TL,BR,BL,CTR" "TR" /wtheme={CWFG=WHITE}
      gcontrol lval tagx "Custom Tag X offset" 0 -50 50 1 /SLIDER /wtheme={CWFG=WHITE}
      gcontrol lval tagy "Custom Tag Y offset" 0 -50 50 1 /SLIDER /wtheme={CWFG=WHITE}
      FEATURE label=pipebox table={NAME=PIPEBOX,TYPE=BOX,COLOR=AQUA,ENABLE=1} plot=timepipe /wtheme={CWFG=WHITE}
      shellgui/id=idshellgui/attach/rows=15

    pipe off

    invoke ,, nxm.sys.libg.LayerT5.setAutoAdjustLineColor(^origT5Setting)
    invoke ,, nxm.sys.libg.LayerPoly.setAutoAdjustLineColor(^origPolySetting)

  endif

endmacro

!******************************************************************************!
! Main process message for this macro. Should be right after the ENDMACRO.
!******************************************************************************!
procedure processMessage m:msg
  if msg.name eqs "MAIN" then
    assert/text="^reg.main.name: User indicated tests" msg.data eqss "PASS"
    pipe stop
  elseif msg.name EQS MAPS then
    if msg.data EQS SHAPE then
      if gc.MAPS.isSet("SHAPE") then
        invoke ,, reg.timepipe.openFile(^shapeFile{Layer={Group=drawablegrp,NAME=SHAPE}})
      else
        res done reg.timepipe.layers.drawablegrp.removeDrawable(SHAPE)
      endif
    elseif msg.data EQS "SAMPLE KML" then
      if gc.MAPS.isSet("SAMPLE KML") then
        invoke ,, reg.timepipe.openFile(nxm.sys.test.kmlTest.kml&
                {LAYER={ICONSIZE=10,ICONZOOMSIZE=48,COLORBLENDRATIO=0.8,ALLOWPOPUPS=TRUE}}|&
                nxm.sys.test.kmlStyledDescription.kml&
                {LAYER={ICONSIZE=10,ICONZOOMSIZE=48,COLORBLENDRATIO=0.8,ALLOWPOPUPS=TRUE}})
      else
        invoke ,, reg.timepipe.closeFile(KMLTEST)
        invoke ,, reg.timepipe.closeFile(KMLSTYLEDDESCRIPTION)
      endif
    elseif msg.data EQS "OPERATIONAL KML" then
      if user_kml NEQS "" then
        if gc.MAPS.isSet("OPERATIONAL KML") then
          message send timepipe name="OPENFILE" data="^{user_kml}"
        else
          invoke mylayers reg.timepipe.layers
          foreach layern INTABLE mylayers
            if layern EQSS "OPKML" then
              message send timepipe name="CLOSEFILE" data=^layern
            endif
          endfor
        endif
      else
        INFO "Operational KML not provided"
      endif
    elseif msg.data EQS "T5 FLIGHT" then
      if gc.MAPS.isSet("T5 FLIGHT") then
        invoke snakeSpeed java.lang.Math.random()
        calc snakeRate 20 snakeSpeed /
        if snakeRate GT 80 then res snakerate 80
        nxm.sys.test.t5pathgenerator/FLIGHT/LAT_START=50/LON_START=150/LAT_DEST=20/LON_DEST=200/LON_SHIFT=0/LAT_SHIFT=0/DIRECTCOLOR=^flightcolor/NOFLAGS/RT/NOTEMODETYPE=VA/RATE=^snakeRate OUT=_flight{SIZE=10000} ELEM=Inf /bg
        invoke ,, reg.timepipe.openFile(_flight{LAYER={^ellipselayerflight,FormRegions=true},TAG=flightPIPE})
      else
        res done reg.timepipe.layers.drawablegrp.removeDrawable(^flight)
      endif
    elseif msg.data EQS "T5 TRAJECTORY" then
      if gc.MAPS.isSet("T5 TRAJECTORY") then
        invoke snakeSpeed java.lang.Math.random()
        calc snakeRate 20 snakeSpeed /
        if snakeRate GT 80 then res snakerate 80
        nxm.sys.test.t5pathgenerator/TRAJECTORY/LAT_START=45/LON_START=100/LAT_DEST=50/LON_DEST=106/LON_SHIFT=0.01/LAT_SHIFT=0.002/DIRECTCOLOR=^trajectorycolor/NOFLAGS/RT/NOTEMODETYPE=VA/RATE=^snakeRate OUT=_trajectory{SIZE=10000} ELEM=Inf /bg
        invoke ,, reg.timepipe.openFile(_trajectory{LAYER={^ellipselayertrajectory,FormRegions=true},TAG=TRAJECTORYPIPE})
      else
        res done reg.timepipe.layers.drawablegrp.removeDrawable(TRAJECTORY)
      endif
    elseif msg.data EQS "OPERATIONAL T5" then
      if user_kml NEQS "" then
        if gc.MAPS.isSet("OPERATIONAL T5") then
          message send timepipe name="OPENFILE" data="^{user_t5}"
        else
          invoke mylayers reg.timepipe.layers
          foreach layern INTABLE mylayers
            if layern EQSS "OPT5" then
              message send timepipe name="CLOSEFILE" data=^layern
            endif
          endfor
        endif
      endif
    elseif msg.data EQS "OPERATIONAL WMS" then
      if gc.MAPS.isSet("OPERATIONAL WMS") then
        res mapsel gc.maps.value
        invoke mapsel mapsel.replace("Operational WMS","")
        if canRunWms isTrue then
          invoke layerList wmslayers.split(",")
          invoke numLayers layerList.size()
          if numLayers eq 4 then
            %test_plot_layerwms_gwc url="^wmsUrl" layers="^wmsLayers" transitions="500,1.5e3,1e8"
          elseif numLayers eq 3 then
            %test_plot_layerwms_gwc url="^wmsUrl" layers="^wmsLayers" transitions="500,1e8"
          elseif numLayers eq 2 then
            %test_plot_layerwms_gwc url="^wmsUrl" layers="^wmsLayers" transitions="L10"
          else
            popup func=ok message="To run the test LAYERWMS_GWC, between 2 and 4 layers must be selected (i.e. supports up to 3 transitions)." type=err
          endif
          invoke ,, gc.MAPS.setValue(^mapsel)
        else
          WARN "WMS setup not available"
        endif
      endif
    endif
  elseif msg.name eqs "FEATTEXTPROMPT" then
    say msg.data
    res gc.featureText.value "^msg.data"
  elseif msg.name eqss "SHAPEFILESELECTION" then
    res shapefile ^msg.data
  elseif msg.name EQS "CLEARLAYERS" then
    if msg.data      EQS "ALL" then
      invoke ,, reg.timepipe.clearData()
    elseif msg.data EQS ^trajectory then
      if gc.MAPS.isSet("T5 TRAJECTORY") then
        res done reg.timepipe.layers.drawablegrp.getLayer(trajectory).clear()
      endif
    elseif msg.data EQS ^flight then
      if gc.MAPS.isSet("T5 FLIGHT") then
        res done reg.timepipe.layers.drawablegrp.getLayer(FLIGHT).clear()
      endif
    else 
      say "CLEARLAYERS unsupported for ^{msg.data}"
    endif
  elseif msg.name eqs "CLUSTER" then
    if clusterDecluster EQS "CLUSTER"
      res clusterDecluster "NO CLUSTERING"
      invoke ,, reg.timepipe.layers.drawablegrp.setShowClusters(^booleanTrue)
      invoke ,, gc.cluster.setItems("NO CLUSTERING")
    else
      res clusterDecluster "CLUSTER"
      invoke ,, reg.timepipe.layers.drawablegrp.setShowClusters(^booleanFalse)
      invoke ,, gc.cluster.setItems("CLUSTER")
    endif
  elseif msg.name eqs "FEATUREBUTT" then
    if msg.data EQS DEFAULT then
      call addFeature ""
    elseif msg.data EQS CUSTOMTAG then
      res tagx gc.tagx.value
      res i:tagy gc.tagy.value
      res tagref gc.customTagRef.value
      call addCustomFeature
    elseif msg.data EQS NONE then
      invoke ,, reg.timepipe.removeAllFeatures()
    else
      call addFeature msg.data
    endif
  else

  endif
return

!******************************************************************************!
! If an unexpected exception is caught, mark test as failed, unless it is expected
!******************************************************************************!
procedure processException m:emsg

  if expectedException REXISTS then
    assert/text="^reg.main.name: Expected ERROR starts with: ^{expectedException}" expectedException EQSS emsg.data.message
    remove expectedException
  else
    assert/text="^reg.main.name: Caught unexpected exception ^{emsg.data}" "FALSE" isTrue
    if "Trace" SUBS ENV.DEBUG then invoke ,, emsg.data.printStackTrace()
  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

!******************************************************************************!
! basic setup of files and defaults
!******************************************************************************!
procedure basicSetup

  call setDatDir

  set defaultFeatureText "Feature Title\nKEY1=first line\nKEY2=very long second line\nKEY3=line3"
  res shapefile "^{datDir}.world.shp" ! SET DEFAULT SHAPE FILE
  res kmlfiles  "nxm.sys.test.kmlLinkTest.kml&
                {LAYER={ICONSIZE=10,ICONZOOMSIZE=48,COLORBLENDRATIO=0.8,ALLOWPOPUPS=TRUE}}|&
                nxm.sys.test.kmlStyledDescription.kml&
                {LAYER={ICONSIZE=10,ICONZOOMSIZE=48,COLORBLENDRATIO=0.8,ALLOWPOPUPS=TRUE}}"
  ! T5 snake files
  res trajectorycolor "AQUA"
  res flightcolor "MAGENTA"
  res trajectory "TRAJECTORY"
  res flight "FLIGHT"
  res clusterDecluster "CLUSTER"
return

!******************************************************************************!
! WMS setup
!******************************************************************************!
procedure wmsSetup
  if wms_config_tbl CONTAINS/K URL AND wms_config_tbl CONTAINS/K LAYERS then
    table wms_config_tbl GETKEY URL wmsurl
    table wms_config_tbl GETKEY LAYERS wmslayers
    res canRunWms true
  else
    res canRunWms false
  endif
return

!*****************************************************************************
! add Feature
!*****************************************************************************
procedure addFeature s:tagtype
res tagtype
  res addon ""
  if tagtype NEQS "" then
    res addon "|^tagtype"
  endif
  res addon
  invoke xvalue nxm.sys.test.t5pathgenerator.randomLon()
  invoke yvalue nxm.sys.test.t5pathgenerator.randomLat()
  res name "^gc.featuretext.value"
  feature label=icon       table={NAME="^name",TYPE=SYMBOL|TEXT^{addOn},X=^xvalue,Y=^yvalue,&
                                  LINE={SYMBOL="^{datDir}.Arrow.png"}} &
                                  plot=timepipe
return

!*****************************************************************************
procedure addCustomFeature

  invoke xvalue nxm.sys.test.t5pathgenerator.randomLon()
  invoke yvalue nxm.sys.test.t5pathgenerator.randomLat()
  feature label=icon       table={NAME="^name",TYPE=SYMBOL|TEXT|CUSTOMTAG,X=^xvalue,Y=^yvalue,&
                                  CUSTOMTAGXPIX=^tagx,CUSTOMTAGYPIX=^tagy,CUSTOMTAGREF=^tagref,LINE={SYMBOL="^{datDir}.Arrow.png"}} &
                                  plot=timepipe
return
