'============================================================================
'ZedGraph Class Library - A Flexible Charting Library for .Net
'Copyright (C) 2005 John Champion and Jerry Vos
'
'This library is free software; you can redistribute it and/or
'modify it under the terms of the GNU Lesser General Public
'License as published by the Free Software Foundation; either
'version 2.1 of the License, or (at your option) any later version.
'
'This library is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
'Lesser General Public License for more details.
'
'You should have received a copy of the GNU Lesser General Public
'License along with this library; if not, write to the Free Software
'Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'=============================================================================
Imports ZedGraph
Imports ZedGraph.Web
Imports System.Drawing

Imports System.IO


Public Class graph
  Inherits System.Web.UI.Page
  Private m_vTitle As String = "Values"
  Private m_title As String = ""
  Private m_xtitle As String = ""
  Private m_ytitle As String = ""

  Private m_list As PointPairList
  Private m_Name As String
  Private m_NetWork As String
  Private m_SiteID As String = Nothing
  Private m_VarCode As String = Nothing
  Private m_StDate As String
  Private m_EndDate As String
  Private iChartType As Integer

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  'NOTE: The following placeholder declaration is required by the Web Form Designer.
  'Do not delete or move it.
  Private designerPlaceholderDeclaration As System.Object

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'response to getvalues request is saved in session variable "hashname" 


        '
        Dim hashname As String = Request.Params.Get("hashname")
        Dim Xml As String = Session(hashname)

        Dim gvr As CUAHSI.GetValuesResponse = New CUAHSI.GetValuesResponse(Xml)

        Dim sOk As String
        sOk = GetChartValues(gvr)
        If (sOk = "OK") Then
            Me.Title = "Time Series Plot: " & m_Name
        Else
            Me.Title = "Problem plotting " & m_Name
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
                ApSConfigAHS.Write2Log("PlotChart:" & sOk, True, -1, False)
            End If
        End If

    End Sub

  Private Sub OnRenderGraph(ByVal zgw As ZedGraphWeb, ByVal g As System.Drawing.Graphics, _
    ByVal masterPane As ZedGraph.MasterPane) Handles ZedGraphWeb1.RenderGraph
  
    ' Get a reference to the GraphPane instance in the ZedGraphControl
    Dim myPane As GraphPane = masterPane(0)
    ' Set the titles and axis labels
    myPane.Title.Text = m_title
    'myPane.XAxis.Title.Text = m_xtitle
    myPane.YAxis.Title.Text = m_ytitle
    ' Generate a red curve with diamond symbols, and "Alpha" in the legend
    Dim myCurve As LineItem = Nothing
    If ((iChartType And 4) = 4) Then
      myCurve = myPane.AddCurve(m_vTitle, m_list, Color.Red, SymbolType.None)
    End If
    If ((iChartType And 2) = 2) Then
      If Not myCurve Is Nothing Then
        myPane.CurveList.Remove(myCurve)
        myCurve = myPane.AddCurve(m_vTitle, m_list, Color.Red, SymbolType.Circle)
      Else
        myCurve = myPane.AddCurve(m_vTitle, m_list, Color.Empty, SymbolType.Circle)
      End If
    End If
    If ((iChartType And 1) = 1) Then
      If (myCurve Is Nothing) Then
        myCurve = myPane.AddCurve(m_vTitle, m_list, Color.Red, SymbolType.None)
      End If
      myCurve.Line.Fill = New Fill(Color.White, Color.BlueViolet, 45.0F)
    End If
    ' Fill the symbols with white
    '  myCurve.Symbol.Fill = New Fill(Color.White)
    ' Generate a blue curve with circle symbols, and "Beta" in the legend
    'myCurve = myPane.AddCurve("Beta", list2, Color.Blue, SymbolType.Circle)
    ' Fill the symbols with white
    myCurve.Symbol.Fill = New Fill(Color.White)
    ' Associate this curve with the Y2 axis
    myCurve.IsY2Axis = True
    ' Show the x axis grid
    myPane.XAxis.MajorGrid.IsVisible = True
    myPane.XAxis.CrossAuto = True
    myPane.XAxis.Type = AxisType.Date
    'myPane.XAxis.min
    ' Make the Y axis scale red
    myPane.YAxis.Scale.FontSpec.FontColor = Color.Red
    myPane.YAxis.Title.FontSpec.FontColor = Color.Red
    myPane.Title.FontSpec.Size = 10
    ' turn off the opposite tics so the Y tics don't show up on the Y2 axis
    myPane.YAxis.MajorTic.IsOpposite = False
    myPane.YAxis.MinorTic.IsOpposite = False
    ' Don't display the Y zero line
    myPane.YAxis.MajorGrid.IsZeroLine = False
    ' Align the Y axis labels so they are flush to the axis
    myPane.YAxis.Scale.Align = AlignP.Inside

    ' Enable the Y2 axis display
    myPane.Y2Axis.IsVisible = True
    ' Make the Y2 axis scale blue
    myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue
    myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue
    ' turn off the opposite tics so the Y2 tics don't show up on the Y axis
    myPane.Y2Axis.MajorTic.IsOpposite = False
    myPane.Y2Axis.MinorTic.IsOpposite = False
    ' Display the Y2 axis grid lines
    myPane.Y2Axis.MajorGrid.IsVisible = True
    ' Align the Y2 axis labels so they are flush to the axis
    myPane.Y2Axis.Scale.Align = AlignP.Inside
    myPane.Y2Axis.CrossAuto = True

    ' Fill the axis background with a gradient
    myPane.Chart.Fill = New Fill(Color.White, Color.LightGray, 45.0F)
    masterPane.AxisChange(g)
  End Sub
  Private Function GetChartValues(ByVal gvr As CUAHSI.GetValuesResponse) As String
    Dim valueCountStr As String = ""
    Dim chartInput As String = ""
    Dim tsInputArray() As String
    Dim oNetwork As HISNetwork
    Dim sMsg As String = "OK"
    Dim sNoData As String = ""
    Try

      Try
        valueCountStr = Request(ApSConfigAHS.K_NumOfRecs)
        chartInput = Request(ApSConfigAHS.K_ChartInput)
        Try
          sNoData = Request(ApSConfigAHS.K_NoDataValue)
          sNoData = sNoData.Trim
        Catch ex As Exception
                    Return ex.Message
        End Try
      Catch ex As Exception
                Return ex.Message
      End Try
      oNetwork = Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      tsInputArray = chartInput.Split(ApSConfigAHS.K_Sep2)
      m_NetWork = tsInputArray(0)
      m_SiteID = tsInputArray(1)
      m_VarCode = tsInputArray(2)
      m_StDate = tsInputArray(3)
      m_EndDate = tsInputArray(4)

      'ChartType: 1 bar, 2 line, 4 xy 
      Try
        iChartType = CType(tsInputArray(5), Integer)
      Catch ex As Exception
        iChartType = 1
      End Try
      Dim mydate As System.DateTime
      Dim myxdate As XDate
      Dim nNoDataCnt As Integer = 0
      m_list = New PointPairList()

      ' Read the time series dates and values from the get values response.
      Dim ts As CUAHSI.GetValuesResponse.TSeries = gvr.TimeSeries
      Dim vals As ArrayList = ts.Values.values
      Dim censorCode As String = "nc"
      For Each val As CUAHSI.GetValuesResponse.TSeries.valuedata.Value In vals
        Dim attribs As Hashtable = val.attribs

        If attribs.ContainsKey("censorCode") Then
          censorCode = attribs.Item("censorCode")
        Else
          censorCode = "nc"
        End If
                If val.value <> gvr.TimeSeries.Variable.nodataval And censorCode = "nc" Then
                    mydate = val.date_time
                    myxdate = New XDate(mydate.Year, mydate.Month, mydate.Day, mydate.Hour, mydate.Minute, mydate.Second)
                    m_list.Add(myxdate, val.value)
                Else
                    nNoDataCnt = nNoDataCnt + 1
                End If
            Next

            m_list.Sort()

      ' Read chart metadata from the get values response.
      ' Variable description.
      Dim varUnits As String = ts.Variable.unitsabbr
      If varUnits <> "" Then
        varUnits = " (" & varUnits & ")" ' Enclose this information in parens for display.
      End If

      ' Set chart display text.
      m_Name = ApSConfigAHS.GetVariableName(oNetwork, m_VarCode)
      Dim sName As String
      sName = ApSConfigAHS.GetSiteName(oNetwork, m_SiteID)
      m_vTitle = "Variable: " & IIf(m_Name = "", m_VarCode, m_Name & " [" & m_VarCode & "]") & vbCrLf
      m_title = "Site: " & IIf(sName = "", m_SiteID, sName & " [" & m_SiteID & "]")
      m_title = m_title & vbCrLf & valueCountStr & " record(s) from " & m_StDate & " to " & m_EndDate
      If (nNoDataCnt > 0) Then
        m_title = m_title & ", NoData Count=" & nNoDataCnt
      End If
      m_ytitle = m_Name & varUnits
      sMsg = "OK"
    Catch ex As Exception
      sMsg = "No value to plot.<br />" & ex.Message
    End Try
    Return sMsg
  End Function

End Class
