Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports ESRI.ArcGIS.ADF.Web
Imports ESRI.ArcGIS.ADF.Web.UI.WebControls
Imports ESRI.ArcGIS.ADF.Web.DataSources
Imports ESRI.ArcGIS.ADF.Web.Geometry
Imports ESRI.ArcGIS.ADF.Web.Display.Graphics
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.ADF.ArcGISServer
Imports System.Collections.Generic

'/ <summary>
'/ Summary description for Identify
'/ </summary>
Public Class HISIdentify
  Private m_page As System.Web.UI.Page   ' Page
  Private m_idOption As IdentifyOption = IdentifyOption.VisibleLayers
  Private m_map As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map
  Private m_dataset As DataSet
  Private m_callbackInvocation As String = ""
  Private m_filePath As String = ""
  Private m_resultsDisplay As TaskResults = Nothing
  Private m_numberDecimals As Integer = 3
  Public m_IdentifyTolerance As Integer = 5 ' tolerance used in identify request... may need to be adjusted to a specific resource type
  Public Sub New() '

  End Sub 'New


  Public Sub New(ByVal map As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)
    If Not (map Is Nothing) Then
      m_map = map
      SetupIdentify()
    End If
  End Sub 'New
  Public Sub New(ByVal map As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map, ByVal filePath As String)
    m_map = map
    m_filePath = filePath
    SetupIdentify()
  End Sub 'New
  Public Sub SetupIdentify() '
    m_page = m_map.Page
    Dim sb As New System.Text.StringBuilder()
    m_callbackInvocation = m_page.ClientScript.GetCallbackEventReference(m_page, "message", "HandleResponse", "context", True)
    sb.Append((ControlChars.Lf + "<script language=""javascript"" type=""text/javascript"" src=""" + m_filePath + "JavaScript/cuahsi.js"" ></script>" + ControlChars.Lf))
    'sb.Append("<link rel=\"Stylesheet\" href=\"" + m_filePath + "styles/IdentifyWindowStyleSheet.css\" type=\"text/css\" />\n");
    sb.Append(("<script language=""javascript"" type=""text/javascript"">var HISIDCallbackFunctionString = """ + m_callbackInvocation + """;</script>" + ControlChars.Lf))
    If Not m_page.ClientScript.IsClientScriptBlockRegistered("HISIdentifyScript") Then
      m_page.ClientScript.RegisterClientScriptBlock(m_page.GetType(), "HISIdentifyScript", sb.ToString())
    End If
  End Sub 'SetupIdentify

  Public Function Identify(ByVal queryString As NameValueCollection, ByVal dBuffer As Double) As String
    Dim ds As Long = DateTime.Now.Ticks
    Dim xString As String = queryString("minx")
    Dim yString As String = queryString("miny")
    Dim locXString As String = ""
    Dim locYString As String = ""
    Dim notSupported As Boolean = False
    Dim x As Integer = Convert.ToInt32(xString)
    Dim y As Integer = Convert.ToInt32(yString)
    Dim mapPoint As ESRI.ArcGIS.ADF.Web.Geometry.Point = ESRI.ArcGIS.ADF.Web.Geometry.Point.ToMapPoint(x, y, m_map.GetTransformationParams(ESRI.ArcGIS.ADF.Web.Geometry.TransformationDirection.ToMap))
    'Dim mapPoint As ESRI.ArcGIS.ADF.Web.Geometry.Point = ESRI.ArcGIS.ADF.Web.Geometry.Point.ToMapPoint(x, y, m_map.Extent, m_map.TilingScheme.ViewWidth, m_map.TilingScheme.ViewHeight)
    Dim gdsList As New List(Of DataSet)
    Dim pMF As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality
    Dim sActiveLayerName As String
    Dim pFL As IFeatureLayer
    Dim pFC As ESRI.ArcGIS.Geodatabase.IFeatureClass
    Dim pMSDP As ESRI.ArcGIS.ADF.ArcGISServer.MapServerDcomProxy '= (ESRI.ArcGIS.ADF.ArcGISServer.MapServerDcomProxy)pGisRecsLocal.MapServerProxy;
    Dim pFeature As IFeature

    Dim pGisRecsLocal As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal
    Dim pFIDSet As ESRI.ArcGIS.ADF.ArcGISServer.FIDSet
    Dim pMapDesc As ESRI.ArcGIS.ADF.ArcGISServer.MapDescription
    Dim pLayerDescs() As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription  'layerDescs = mapDesc.LayerDescriptions;
    Dim pLayerDesc As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription
    Dim pSC As ESRI.ArcGIS.Server.IServerContext
    Dim pMapLayerInfos() As ESRI.ArcGIS.ADF.ArcGISServer.MapLayerInfo
    Dim iLayerIndex As Integer
    Dim pSPF As ESRI.ArcGIS.ADF.ArcGISServer.SpatialFilter
    Dim minPnt As ESRI.ArcGIS.ADF.Web.Geometry.Point = New ESRI.ArcGIS.ADF.Web.Geometry.Point
    Dim maxPnt As ESRI.ArcGIS.ADF.Web.Geometry.Point = New ESRI.ArcGIS.ADF.Web.Geometry.Point
    Dim pMapRect As ESRI.ArcGIS.ADF.Web.Geometry.Envelope
    Dim roundFactor As Double = Math.Pow(10, m_numberDecimals)
    Dim pointXString As String = Convert.ToString((Math.Round((mapPoint.X * roundFactor)) / roundFactor))
    Dim pointYString As String = Convert.ToString((Math.Round((mapPoint.Y * roundFactor)) / roundFactor))
    locXString = pointXString
    locYString = pointYString
    Dim iCnt As Integer
    Dim i As Integer
    Dim sMsgLong As String
    Dim sMsg As String = ""
    Dim oActiveNetwork As HISNetwork
    Dim pParamFields As ApWebFields
    Dim pDispFields As ApWebFields
    Dim sValue As String
    Try
      pMF = Map.GetFunctionality(ApSConfigAHS.MapServiceName)
      pMapDesc = pMF.MapDescription
      pLayerDescs = pMapDesc.LayerDescriptions
      oActiveNetwork = m_page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      sActiveLayerName = oActiveNetwork.LayerName
      pParamFields = oActiveNetwork.ParameterFields
      pDispFields = oActiveNetwork.DisplayFields
      pGisRecsLocal = pMF.Resource  '  pGisRecs
      pMapLayerInfos = pGisRecsLocal.MapServerInfo.MapLayerInfos
      iLayerIndex = ApSConfigAHS.GetLayerIndex(pMapLayerInfos, sActiveLayerName)
      If (iLayerIndex < 0) Then
        sMsgLong = "<HTML> Layer:" & sActiveLayerName & " is not found. </HTML>"
        Exit Try
      End If
      pLayerDesc = pLayerDescs(iLayerIndex)
      pSC = pGisRecsLocal.ServerContextInfo.ServerContext
      pFL = ApSConfigAHS.GetLayer(pMF, sActiveLayerName)
      pFC = pFL.FeatureClass

      Dim b As Boolean
      Dim sScript As String

      ''..try to project on the fly.
      'Dim pGeoDataset As IGeoDataset
      'Dim pMap As IMap
      'Dim pMapServer As ESRI.ArcGIS.Carto.IMapServer = pGisRecsLocal.MapServer
      'Dim pMapServerObjects As IMapServerObjects = pMapServer
      'Dim pFCSpatialRef As ESRI.ArcGIS.Geometry.ISpatialReference
      'Dim pMapSpatialRef As ESRI.ArcGIS.Geometry.ISpatialReference
      'pMap = pMapServerObjects.Map(pMapServer.DefaultMapName)

      'pGeoDataset = pFC
      'pFCSpatialRef = pGeoDataset.SpatialReference
      'pMapSpatialRef = pMap.SpatialReference
      'If (pFCSpatialRef.FactoryCode = pMapSpatialRef.FactoryCode) Then


      'End If

      b = ApSConfigAHS.SetApWebFieldsIndex(CType(pFC, ITable), pParamFields)
      b = ApSConfigAHS.SetApWebFieldsIndex(CType(pFC, ITable), pDispFields)
      sScript = oActiveNetwork.Script
      dBuffer = m_map.Extent.Width * dBuffer
      minPnt.X = mapPoint.X - dBuffer
      minPnt.Y = mapPoint.Y - dBuffer
      maxPnt.X = mapPoint.X + dBuffer
      maxPnt.Y = mapPoint.Y + dBuffer
      pMapRect = New ESRI.ArcGIS.ADF.Web.Geometry.Envelope(minPnt, maxPnt)

      Dim env As EnvelopeN
      env = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.FromAdfEnvelope(pMapRect)

      pSPF = New ESRI.ArcGIS.ADF.ArcGISServer.SpatialFilter
      pSPF.FilterGeometry = env  'ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.FromAdfPoint(mapPoint)
      pSPF.SpatialRel = ESRI.ArcGIS.ADF.ArcGISServer.esriSpatialRelEnum.esriSpatialRelIntersects
      pMSDP = pGisRecsLocal.MapServerProxy
      pFIDSet = pMSDP.QueryFeatureIDs(pMapDesc.Name, pLayerDesc.LayerID, pSPF)
      sMsgLong = "<HTML><Table>"
      iCnt = pFIDSet.FIDArray.Length
      If iCnt = 0 Then
        sMsgLong = sMsgLong & "<TH ALIGN=""LEFT"" WIDTH=""900"" NOWRAP>" & "Location (" & locXString & ", " & locYString & ") No results found" & "</TH>"
      Else
        If iCnt = 1 Then
          sMsgLong = sMsgLong & "<TH ALIGN=""LEFT"" WIDTH=""900"" NOWRAP><Font bold=true>" & iCnt & " feature at (" & locXString & ", " & locYString & ")</Font>" & "</TH>"
        Else
          sMsgLong = sMsgLong & "<TH ALIGN=""LEFT"" WIDTH=""900"" NOWRAP><Font bold=true>" & iCnt & " features at (" & locXString & ", " & locYString & ")</Font>" & "</TH>"
        End If
        Dim iFld As Integer
        Dim iDispCnt As Integer
        Dim iParamCnt As Integer
        Dim sParams As String
        Dim sDisps As String
        Dim bHasOrders As Boolean
        Dim pApWebField As ApWebField
        iDispCnt = pDispFields.Count
        iParamCnt = pParamFields.Count
        bHasOrders = True
        For Each pApWebField In pDispFields.Values
          If pApWebField.FieldOrder < 0 Then
            bHasOrders = False
            Exit For
          End If
        Next
        For i = 0 To iCnt - 1
          Try
            pFeature = pFC.GetFeature(pFIDSet.FIDArray(i))
            sParams = ""
            If Not pFeature Is Nothing Then
              For iFld = 0 To iParamCnt - 1
                '..GetParams
                pApWebField = pParamFields.GetApWebFieldByOrder(iFld)
                If Not pApWebField Is Nothing Then
                  If pApWebField.ConstValue = True Then
                    sValue = IIf(pApWebField.Value <> "", pApWebField.Value, pApWebField.Text)
                    If sParams = "" Then
                      sParams = "'" & sValue & "'"
                    Else
                      sParams = sParams & ",'" & sValue & "'"
                    End If
                  Else
                    If pApWebField.Index >= 0 Then
                      Try
                        sValue = "" & pFeature.Value(pApWebField.Index)
                      Catch ex As Exception
                        sValue = ""
                      End Try
                      If sParams = "" Then
                        sParams = "'" & sValue & "'"
                      Else
                        sParams = sParams & ",'" & sValue & "'"
                      End If
                    End If
                  End If
                End If
              Next  'iFld = 0 To iParamCnt - 1
              '..get Disps
              sDisps = ""
              If bHasOrders = True Then
                For iFld = 0 To iDispCnt - 1
                  pApWebField = pDispFields.GetApWebFieldByOrder(iFld)
                  If Not pApWebField Is Nothing Then
                    If pApWebField.ConstValue = True Then
                      sValue = IIf(pApWebField.Value <> "", pApWebField.Value, pApWebField.Text)
                      If sDisps = "" Then
                        sDisps = sValue
                      Else
                        sDisps = sDisps & "," & sValue
                      End If
                    Else
                      If pApWebField.Index >= 0 Then
                        Try
                          sValue = "" & pFeature.Value(pApWebField.Index)
                        Catch ex As Exception
                          sValue = ""
                        End Try
                        If sDisps = "" Then
                          sDisps = sValue
                        Else
                          sDisps = sDisps & "," & sValue
                        End If
                      End If
                    End If
                  End If
                Next
              Else
                For Each pApWebField In pDispFields.Values
                  If pApWebField.ConstValue = True Then
                    sValue = IIf(pApWebField.Value <> "", pApWebField.Value, pApWebField.Text)
                    If sDisps = "" Then
                      sDisps = sValue
                    Else
                      sDisps = sDisps & "," & sValue
                    End If
                  Else
                    If pApWebField.Index >= 0 Then
                      Try
                        sValue = "" & pFeature.Value(pApWebField.Index)
                      Catch ex As Exception
                        sValue = ""
                      End Try
                      If sDisps = "" Then
                        sDisps = sValue
                      Else
                        sDisps = sDisps & "," & sValue
                      End If
                    End If
                  End If
                Next
              End If
              'pPoint = pFeature.Shape
              sMsg = "<A href=""javascript:" & sScript & "(" & sParams & ")"">" & sDisps & "</A>" ' & " (" & Format(pPoint.X, "0.000") & ", " & Format(pPoint.Y, "0.000") & "</A><BR />"
            End If
            If i Mod 2 = 0 Then
              sMsgLong = sMsgLong & "<TR><TD WIDTH=""900"" NOWRAP BGCOLOR=""#FFFFCC"">" & sMsg & "</TD></TR>"
            Else
              sMsgLong = sMsgLong & "<TR><TD WIDTH=""900"" NOWRAP>" & sMsg & "</TD></TR>"
            End If

          Catch ex As Exception
            sMsgLong = sMsgLong & "<TR><TD WIDTH=""900"" NOWRAP BGCOLOR=""#CCCC33"">" & ex.Message & ", " & ex.StackTrace & "</TD></TR>"
          End Try
        Next
        '..Appending a const site for testing....
        'sMsgLong = sMsgLong & "<A HREF=""javascript:GetSiteInfo(" & "'10250600','NWIS')" & """>getTestInfo</A>"
      End If
      sMsgLong = sMsgLong & "</HTML>"
    Catch ex As Exception
      sMsgLong = "<HTML>" & [GetType].ToString & "<BR />" & ex.Message & ", " & ex.StackTrace & "<br>" & ApSConfigAHS.MapServiceName & "<br>Map Is Nothing=" & (Map Is Nothing) & "</HTML>"
    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("HISIdentify.Identify: " & iCnt & " features.", True, ds, False)
      End If
    End Try
    Return sMsgLong

  End Function 'Identify 

  Public Property Map() As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map
    Get
      Return m_map
    End Get
    Set(ByVal value As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)
      m_map = value
    End Set
  End Property

  Public Property Page() As System.Web.UI.Page
    Get
      Return m_page
    End Get
    Set(ByVal value As System.Web.UI.Page)
      m_page = value
    End Set
  End Property

  Public Property DataSet() As DataSet
    Get
      Return m_dataset
    End Get
    Set(ByVal value As DataSet)
      m_dataset = value
    End Set
  End Property

  Public Property IdentifyOption() As IdentifyOption
    Get
      Return m_idOption
    End Get
    Set(ByVal value As IdentifyOption)
      m_idOption = value
    End Set
  End Property

  Public Property ClientCallbackInvocation() As String
    Get
      Return m_callbackInvocation
    End Get
    Set(ByVal value As String)
      m_callbackInvocation = value
    End Set
  End Property

  Public Property FilePath() As String
    Get
      Return m_filePath
    End Get
    Set(ByVal value As String)
      m_filePath = value
    End Set
  End Property

  Public Property ResultsDisplay() As TaskResults
    Get
      Return m_resultsDisplay
    End Get
    Set(ByVal value As TaskResults)
      m_resultsDisplay = value
    End Set
  End Property

  Public Property NumberDecimals() As Integer
    Get
      Return m_numberDecimals
    End Get
    Set(ByVal value As Integer)
      m_numberDecimals = value
    End Set
  End Property
End Class 'HISIdentify '
