' Name: Plot_Single
'
' Title: Plot a water quality data time series graph (menu)
'
' Topics: Views
'
' Description: Reads chemical data from an INFO file,
' and plots graphs
' Initial idea from:
' Palle Due Larsen in "Graphics the hard way: Time Series in Avenue"
' at http://www.esri.com/library/userconf/proc96/TO250/PAP246/P246.HTM
'
' Author: Michael Silberbauer 2001-04-25
' Institute for Water Quality Studies, Department of Water and Sanitation
' Private Bag X313 PRETORIA South Africa 0001
' 2001-04-25
'
' Requires: A View, a data file
'
' Self:
'
' Results:
' -----------------------------------------------------------------------------

UserTypeList = {"Domestic_Health","Domestic_Salts","Irrigation","None"}
DefaultColourList = {Color.GetBlue,Color.GetCyan,Color.GetGreen,Color.GetYellow,Color.GetMagenta,Color.GetRed,Color.GetGray,Color.GetBlack}
theProject = av.GetProject
DocumentList = theProject.GetDocs
TableList = List.Make
for each anItem in DocumentList
  if (anItem.is(table)) then
    TableList.Add(anItem)
  end
end
InorganicData = MsgBox.ListAsString(TableList,"Select a table","VTabs")
if (InorganicData<>nil) then
  theVTab = InorganicData.getVTab
else
  MsgBox.Info("No tables available in this project","ERROR: NO TABLE")
  exit
end

' Funny things happen to variable names during file conversion: _ValType
' keeps track of this:

_ValType = "Val_info"
if (InorganicData.AsString.Contains(".dbf")) then
  ' text file

  _ValType = "Val_info_dbf"
end
if (InorganicData.AsString.Contains(".txt")) then
  ' text file

  _ValType = "Val_info_txt"
end
theVTab.GetSelection.ClearAll
theVTab.UpdateSelection
FieldList = theVTab.GetFields
shortlist = List.Make
for each fieldname in FieldList
  if (fieldname.asString.Contains("date").Not) then
    shortlist.Add(fieldname)
    'MsgBox.Info( fieldname.AsString, "FIELD" )

  end
end
'selfields = MsgBox.MultiListAsString( shortlist, "Choose fields (Shift to select many)", "SELECT FIELDS TO PLOT" )

selfields = MsgBox.ListAsString(shortlist,"Choose a field from"++InorganicData.AsString,"SELECT FIELD TO PLOT")
if (selfields=nil) then
  MsgBox.Info("NO FIELDS SELECTED","Stopping execution")
  return nil
else
  PlotItem = selfields
  'MsgBox.Info( PlotItem.AsString, "Item to plot:" )

end
_UseType = MsgBox.ListAsString(UserTypeList,"Choose a user type for guidelines","SELECT USER TYPE")
av.Run("SetConstants",{})
CutList = _UseVariables.Get(PlotItem.AsString)
'MsgBox.ListAsString( CutList, "CutList", "DEBUG" )

RGBList = _theColourDict.Get(PlotItem.AsString)
'MsgBox.ListAsString( RGBList, "RGBList", "DEBUG" )

ColList = List.Make
labels = {"Station","Start year","Start month","Start day","End year","End month","End day","Y Max"}
default = {"A2H027Q01","1996","1","1","2000","12","31","Auto"}
if (CutList<>nil) then
  vType = CutList.Get(1)
  nCuts = CutList.Get(2)
  Guideline1 = CutList.Get(3)
  for each nCut in 3..(nCuts+2)
    labels.Add("Cutpoint"++(nCut-2).AsString)
    default.Add(CutList.Get(nCut).AsString)
  end
else
  vType = 1
  nCuts = 1
  labels.Add("Cutpoint default")
  default.Add("42")
  ColList.Add(DefaultColourList.Get(0))
  ColList.Add(DefaultColourList.Get(4))
end
theVarField = theVTab.FindField(PlotItem.AsString)
the_nDateField = theVTab.FindField("Ndate")
theDateField = theVTab.FindField("Date")
theTimeField = theVTab.FindField("Time")
theBitMap = theVTab.GetSelection
selection = MsgBox.MultiInput("Choose station, dates and graph limits for"++PlotItem.AsString++"in"++InorganicData.AsString+":","SELECTION PARAMETERS",labels,default)
if (selection=nil) then
  MsgBox.Info("Nothing selected","PLOT STOPPING")
  exit
else
  Station = selection.Get(0)
  StartYear = selection.Get(1)
  StartMonth = selection.Get(2)
end
if (StartMonth.Count=1) then
  StartMonth = "0"+StartMonth
end
StartDay = selection.Get(3)
if (StartDay.Count=1) then
  StartDay = "0"+StartDay
end
StartDate = StartYear+StartMonth+StartDay
Date1 = Date.Make(StartDate,"yyyyMMdd")
EndYear = selection.Get(4)
EndMonth = selection.Get(5)
if (EndMonth.Count=1) then
  EndMonth = "0"+EndMonth
end
EndDay = selection.Get(6)
if (EndDay.Count=1) then
  EndDay = "0"+EndDay
end
EndDate = EndYear+EndMonth+EndDay
Date2 = Date.Make(EndDate,"yyyyMMdd")
if ((Date1.AsString="nil") or (Date2.AsString="nil")) then
  MsgBox.Info("Invalid date range"++StartDate++EndDate,"Stopping execution")
  return nil
end
Guidelines = List.Make
Ymax_set = selection.Get(7)
for each nCol in 8..(nCuts+7)
  Guidelines.Add(selection.Get(nCol).AsNumber)
end
for each nCol in 8..(nCuts+8)
  if (RGBList<>nil) then
    ColIndx1 = (nCol-7)*3
    ColIndx2 = ColIndx1+1
    ColIndx3 = ColIndx1+2
    R = RGBList.Get(ColIndx1)
    G = RGBList.Get(ColIndx2)
    B = RGBList.Get(ColIndx3)
    aCol = Color.Make
    aCol.SetRGBList({R,G,B})
    ColList.Add(aCol)
  else
    ColList.Add(DefaultColourList.Get((nCol-8)))
  end
end
if (Date2<Date1) then
  Date0 = Date2
  Date2 = Date1
  Date1 = Date0
end
MinX = Date1
MinX.SetFormat("J")
MinX = MinX.AsString.AsNumber
MaxX = Date2
MaxX.SetFormat("J")
MaxX = 1+MaxX.AsString.AsNumber
DrawStick = false
DrawArea = false
DrawRect = false
TypeList = {"Stick","Area","Box"}
GraphType = MsgBox.ChoiceAsString(TypeList,"Please select a graph type:","GRAPH TYPES AVAILABLE")
if ((GraphType=TypeList.Get(0)) or (GraphType=nil)) then
  DrawStick = true
end
if (GraphType=TypeList.Get(1)) then
  DrawArea = true
end
if (GraphType=TypeList.Get(2)) then
  if (MaxX-MinX<93) then
    DrawRect = true
  else
    ' Rectangles don't work if too thin...

    DrawStick = true
  end
end
Date1.SetFormat("yyyyMMdd")
Date2.SetFormat("yyyyMMdd")
expr = "( ( [Station] ="++Station.AsString.Quote++") and ( [Date] >="++Date1.AsString+".AsDate ) and ( [Date] <="++Date2.AsString+".AsDate ))"
theVTab.Query(expr,theBitMap,#VTAB_SELTYPE_NEW)
theVTab.UpdateSelection
totalBits = theBitMap.GetSize
selBits = theBitMap.Count
Date1.SetFormat("yyyy-MM-dd")
Date2.SetFormat("yyyy-MM-dd")
if (selBits=0) then
  MsgBox.Info(Station.AsString++Date1.AsString++Date2.AsString,"NO SELECTION POSSIBLE")
  exit
end
ViewName = Station.AsString+"_"+PlotItem.AsString+"_"+Date1.AsString+"_"+Date2.AsString+"_"+GraphType+vType.AsString+"_"+_UseType
myDoc = av.GetProject.FindDoc(Viewname)
if (myDoc<>nil) then
  'if( MsgBox.MiniYesNo ("Delete"++ViewName+"?", TRUE ) ) then

  av.GetProject.RemoveDoc(myDoc)
  'end

end
Date1.SetFormat("yyyyMMdd")
Date2.SetFormat("yyyyMMdd")
theView = View.Make
theView.SetName(ViewName)
theView.SetTOCWidth(0)
ScreenWidth = System.ReturnScreenSizePixels.GetX
ScreenHeight = System.ReturnScreenSizePixels.GetY
WinWidth = 0.9*ScreenWidth
WinHeight = 0.2*WinWidth
aWindow = theView.GetWin
aWindow.Resize(WinWidth,WinHeight)
aWindow.Activate
theGraphics = theView.GetGraphics
theDisplay = theView.GetDisplay
' Return the extent (the enclosing rectangle) of the View:

theMapExtent = theView.GetDisplay.ReturnVisExtent

' Extract the dimensions of the View from the extent:
'+----------------------------+x2m,y2m
'|                            |
'|                            |
'|                            |
'|                            |Height
'|                            |
'|                            |
'|                            |
'+----------------------------+
'x1m,y1m        Width

theLowerLeft = theMapExtent.ReturnOrigin
x1m = theLowerLeft.Getx
y1m = theLowerLeft.Gety
Width = theMapExtent.GetWidth
Height = theMapExtent.GetHeight
x2m = x1m+Width
xmm = x1m+(Width/2)
y2m = y1m+Height
ymm = y1m+(Height*0.95)
xlm = x1m+(Width*0.05)
ylm = y1m+(Height/2)
theUpperRight = x2m@y2m
theUpperMiddle = xmm@ymm
theMiddleLeft = xlm@ylm
OriginX = x1m+(Width*0.05)
OriginY = y1m+(Height*0.15)
XaxisLength = Width*0.9
YAxisLength = Height*0.8
yTickLength = XaxisLength*0.01

' Fill the plotting area with a white patch:

aRect = Rect.MakeXY(x1m,y1m,x2m,y2m)
gRect = GraphicShape.Make(aRect)
aSymbol = RasterFill.Make
aSymbol.SetColor(Color.GetWhite)
aSymbol.SetOLColor(Color.GetBlack)
gRect.SetSymbol(aSymbol)
theGraphics.Add(gRect)
av.ShowStopButton
av.ShowMsg("Seeking graph limits for"++PlotItem.AsString++"...")
FoundRecord = false
'MinX = 9999999999
'MaxX = -9999999999

MinY = 9999999999
MaxY = -9999999999
record = 0
if (selBits>0) then
  for each rec in theBitMap
    record = record+1
    av.SetStatus(100*(record/selBits))
    Variable = theVTab.ReturnValue(theVarField,rec)
    nDate = theVTab.ReturnValue(the_nDateField,rec)
    if (Variable>=0) then
      FoundRecord = true
      if (MaxY<Variable) then
        MaxY = Variable
      end
      if (MinY>Variable) then
        MinY = Variable
      end
      if (MaxX<nDate) then
        'MaxX = nDate

      end
      if (MinX>nDate) then
        'MinX = nDate

      end
    end
  end
end
if (FoundRecord.Not) then
  MsgBox.Info("MinX="++MinX.SetFormat("d").AsString++"MaxX="++MaxX.SetFormat("d").AsString++"MinY="++MinY.AsString++"MaxY="++MaxY.AsString,"Graph Limits Problem?")
  exit
end

'Override calculated Y-range in certain cases:

MinY = 0
if (PlotItem.AsString="Ph") then
  PlotItem = "pH"
  MaxY = 14
end
if (Ymax_set.AsString<>"Auto") then
  MaxY = Ymax_set.AsNumber
  ' In the case of pH, we will allow values from 0 to 14:

  if (PlotItem.AsString="Ph") then
    PlotItem = "pH"
    MaxY = 14
  end
end
ScaleX = XaxisLength/(MaxX-MinX)
ScaleY = YaxisLength/(MaxY-MinY)
xTickLength = (MaxY-MinY)/25
xax1 = OriginX+((MinX-MinX)*ScaleX)
xax2 = OriginX+((MaxX-MinX)*ScaleX)
yax1 = OriginY+((MinY-MinY)*ScaleY)
yax2 = OriginY+((MaxY-MinY)*ScaleY)
av.Run("Y_Axis",{MinX,MaxX,MinY,MaxY,OriginX,OriginY,ScaleX,ScaleY,YTickLength,PlotItem})
av.Run("X_Axis",{MinX,MaxX,MinY,MaxY,OriginX,OriginY,ScaleX,ScaleY,XTickLength})
if (DrawArea) then
  av.Run("Plot_Area",{MinX,MaxX,MinY,MaxY,OriginX,OriginY,ScaleX,ScaleY,theVTab,theBitMap,PlotItem,Guidelines})
end
if (DrawRect) then
  av.Run("Plot_Bar",{MinX,MaxX,MinY,MaxY,OriginX,OriginY,ScaleX,ScaleY,theVTab,theBitMap,PlotItem,Guidelines})
end
if (DrawStick) then
  if (vType>1) then
    av.Run("Plot_Stick_Type"+vType.AsString,{MinX,MaxX,MinY,MaxY,OriginX,OriginY,ScaleX,ScaleY,theVTab,theBitMap,PlotItem,Guidelines,ColList})
  else
    av.Run("Plot_Stick",{MinX,MaxX,MinY,MaxY,OriginX,OriginY,ScaleX,ScaleY,theVTab,theBitMap,PlotItem,Guidelines,ColList})
  end
end
Date1.SetFormat("yyyy-MM-dd")
Date2.SetFormat("yyyy-MM-dd")
aTitle = GraphicText.Make(Station.AsString++PlotItem.AsString++Date1.AsString++"to"++Date2.AsString,xax1@ymm)
aTitleSymbol = aTitle.ReturnSymbols.Get(0)
aTitleSymbol.SetSize(8)
theGraphics.Add(aTitle)
'yTitle = GraphicText.Make( PlotItem.AsString, xlm@ylm )
'yTitleSymbol = yTitle.ReturnSymbols.Get( 0 )
'yTitleSymbol.SetSize( 8 )
'theGraphics.AddBatch( yTitle )

av.ClearMsg
av.ClearStatus
theGraphics.EndBatch
theView.Invalidate
aWindow.Activate