' Name: PiePlot
'
' Title: Draw sector pie symbols on map
'
' Topics: Views
'
' Description: Reads median chemical data from a file created outside
'              ArcView, and plots Juanita Pie symbols at the monitoring points based on compliance
'              with water quality guidelines
'              Originally an AML written by Juanita Moolman
'              Institute for Water Quality Studies, Department of Water and Sanitation
'              Private Bag X313 PRETORIA South Africa 0001
'              MoolmanJ@dwaf.gov.za
'              - Reworked for Avenue
' Author: Michael Silberbauer 2001-03-12
'
' Requires: A View, a data file, JuanitaPie.ave
'
' Self:
'
' Results:
' -----------------------------------------------------------------------------

theView = av.GetActiveDoc
thePrj = theView.GetProjection

' Get the GraphicList for the View...
' Return the extent (the enclosing rectangle) of the View:

theMapExtent = theView.GetDisplay.ReturnVisExtent

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

theLowerLeft = theMapExtent.ReturnOrigin
x1m = theLowerLeft.Getx
y1m = theLowerLeft.Gety
xwm = theMapExtent.GetWidth
ywm = theMapExtent.GetHeight
x2m = x1m+xwm
y2m = y1m+ywm
theUpperRight = x2m@y2m
y = 1
x = y*(xwm/ywm)
theDiagonal = ((x^2)+(y^2)).sqrt
'_Scale = theDiagonal / 100
'_Scale = ( x2m - x1m ) / 42

_Scale = (x2m-x1m)/77

'theTable   = theProject.FindDoc( "olifants_data.txt" )
'theTable   = theProject.FindDoc( "b1testph.txt" )
'theTable   = theProject.FindDoc( "list2001-10-12-national-mauchax.txt" )

DocumentList = av.GetProject.GetDocs
TableList = List.Make
for each anItem in DocumentList
  if (anItem.is(table)) then
    TableList.Add(anItem)
  end
end
theTable = MsgBox.ListAsString(TableList,"Select a file with water quality data","DATA TABLES")
if (theTable=nil) then
  MsgBox.Info("No tables available in this project","ERROR: NO TABLE")
  exit
end
UseMissing = MsgBox.YesNo("Use incomplete records (Recommended) ?","JuanitaPie: Incomplete Records",TRUE)
_LblSymbol = MsgBox.YesNo("Label symbols with variable names (usually for key) ?","JuanitaPie: Label Symbols",FALSE)
_IDSymbol = MsgBox.YesNo("Label symbols with station code ?","JuanitaPie: ID Symbols",FALSE)
IDtype = "station"
if (_IDSymbol) then
  IDtype = MsgBox.ListAsString({"num_nat","number","station"},"National number, full number or station?","Juanita Pie: Choose labelling")
end
UseTypeList = ({"Domestic_Health","Domestic_Salts","Irrigation"})
_UseType = MsgBox.ListAsString(UseTypeList,"Please choose a use type","Juanita Pie: Choose use type")
_ValType = "Val_info_mn" ' Code for looking up median cutpoint data in classcodes.txt

_nPetals = 0
_UseVariables = ""
av.Run("SetConstants",{})
_UseKeys = _UseVariables.ReturnKeys
for each key in _UseKeys
'MsgBox.Info( key.AsString, "key"++_nPetals.AsString )

  _nPetals = _nPetals+1
end
theProject = av.getProject
if (_LblSymbol) then
  theTable = theProject.FindDoc("keydata.txt")
  theTable = theProject.FindDoc("keytestdata.txt")
  'theTable   = theProject.FindDoc( "mnmichaelj1h019q01.txt" )

end
theVTab = theTable.getVTab
numrecs = theVTab.GetNumRecords
FieldList = theVTab.GetFields
shortlist = List.Make
for each fieldname in FieldList
  if (fieldname.asString.Left(3)="med") then
    shortlist.Add(fieldname)
    'MsgBox.Info( fieldname.AsString, "FIELD" )

  end
end
'MsgBox.ListAsString( shortlist, "Field list", "Median fields" )
'set file for debug data

aFileName = FN.make("Temp.txt")
if (File.CanDelete(aFileName)) then
  File.Delete(aFileName)
end
linFile = LineFile.Make(aFileName,#FILE_PERM_WRITE)
av.ShowStopButton
av.ShowMsg("Starting process...")
for each record in theVTab
'for each record in 1 .. 10

  theField = theVtab.FindField(IDtype)
  _station = theVtab.ReturnValue(theField,record).AsString
  theField = theVtab.FindField("Latitude")
  lat = theVtab.ReturnValue(theField,record)
  theField = theVtab.FindField("Longitude")
  lon = theVtab.ReturnValue(theField,record)
  geopoint = Point.Make(lon,lat)
  prjpoint = geopoint.ReturnProjected(thePrj)
  _xSymbol = prjpoint.GetX
  _ySymbol = prjpoint.GetY
  _ItemsList = List.Make
  _ClassList = List.Make
  _ColourList = List.Make
  _SeqnsList = List.Make
  _ValueList = List.Make
  classtring = _station
  Valid = true
  if (UseMissing.Not) then
    'Check that all the values required for the symbol are available (nXxx field for medXxx):

    for each fieldname in shortlist 'FieldList
      for each key in _UseKeys
        if (fieldname.asString=key.AsString) then
          keyList = _UseVariables.Get(key)
          theField = theVTab.FindField(key)
          theValue = theVtab.ReturnValue(theField,record)
          if (theValue<0) then
            Valid = false
          end
        end
      end
    end
  end
  if (Valid) then
    for each fieldname in shortlist 'FieldList
      if (fieldname.asString.Left(3)="med") then
        for each key in _UseKeys
        'MsgBox.Info( fieldname.AsString, key.AsString ) 'dont use this msgbox for full data set!

          if (fieldname.asString=key.AsString) then
            'Check that 5 or more values were used for the median:

            FldLen = key.AsString.Count-3
            nKey = "n"+key.AsString.Right(FldLen)
            'MsgBox.Info( nKey.AsString, "FIELD"++fieldname.AsString )

            theField = theVTab.FindField(nkey.AsString)
            if (theField<>nil) then
              theValue = theVtab.ReturnValue(theField,record)
            else
              'some fields don't have an "n"

              theValue = 5
            end
            if ((theValue>=5) or _LblSymbol) then
              keyList = _UseVariables.Get(key)
              theField = theVTab.FindField(key)
              theValue = theVtab.ReturnValue(theField,record)
              seqnum = keyList.Get(0)
              type = keyList.Get(1)
              ncuts = keyList.Get(2)
              ncutsn = ncuts+2 ' was 3
              'Match the value to the cutpoints:

              if (type=1) then
                if (theValue>=0) then
                  class = 0
                end
                class = ncuts
                for each ncut in ncutsn..3 by -1 'why must arrays start at 0?!
                  cutpoint = keyList.Get(ncut)
                  if (theValue<cutpoint) then
                    class = ncut-3
                  end
                end
                colour = class
              end
              if (type=2) then ' the tricky case of domestic pH:
                if (theValue>=0) then
                  colour = 0
                  class = 0
                end
                if (theValue<keyList.Get(3)) then
                  colour = 0
                  class = 4
                end
                if ((theValue>keyList.Get(3)) and (theValue<=keyList.Get(4))) then
                  colour = 1
                  class = 3
                end
                if ((theValue>keyList.Get(4)) and (theValue<=keyList.Get(5))) then
                  colour = 2
                  class = 2
                end
                if ((theValue>keyList.Get(5)) and (theValue<=keyList.Get(6))) then
                  colour = 3
                  class = 1
                end
                if ((theValue>keyList.Get(6)) and (theValue<keyList.Get(7))) then
                  colour = 4
                  class = 0
                end
                if ((theValue>=keyList.Get(7)) and (theValue<keyList.Get(8))) then
                  colour = 5
                  class = 1
                end
                if ((theValue>=keyList.Get(8)) and (theValue<keyList.Get(9))) then
                  colour = 6
                  class = 2
                end
                if ((theValue>=keyList.Get(9)) and (theValue<keyList.Get(10))) then
                  colour = 7
                  class = 3
                end
                if (theValue>keyList.Get(10)) then
                  colour = 8
                  class = 4
                end                
              end
              if (type=3) then ' the tricky case of agricultural pH:
                if (theValue>=0) then
                  class = 0
                end
                cutpoint1 = keyList.Get(3)
                cutpoint2 = keyList.Get(4)
                if ((theValue>cutpoint1) and (theValue<cutpoint2)) then
                  class = 0
                  colour = 1
                end
                if ((theValue<=cutpoint1)) then 'acid
                  class = 1
                  colour = 0
                end
                if ((theValue>=cutpoint2)) then 'base
                  class = 2
                  colour = 2
                end
              end
              if (class>0) then
                'MsgBox.Info( key.AsString++"="++class.AsString++"("++theValue.AsString++")", _station )

              end
              if (theValue<0) then
                'Set the class to "missing" (-1):

                class = -1
                colour = class
              end
              classtring = classtring++key.AsString++"="++class.AsString
              _ClassList.Add(class)
              _ColourList.Add(colour)
              _ItemsList.Add(key)
              _SeqnsList.Add(seqnum)
              _ValueList.Add(theValue)
            end
          end
        end
      end
    end
    nowDate = Date.Now
    nowDate.SetFormat("yyyy-MM-dd")
    nowTime = Date.Now
    nowTime.SetFormat("hhhh:m:s")
    dtStamp = nowDate.asString++" "++nowTime.AsString
    av.SetStatus(100*(record/numrecs))
    av.ShowMsg(dtStamp++"("+record.AsString+")"++classtring)
    textstring = _UseType++dtStamp++"("+(record+1).AsString+")"++classtring
    linFile = LineFile.Make(aFileName,#FILE_PERM_MODIFY)
    linFile.GotoEnd
    linFile.WriteElt(textstring)
    linFile.Close 'close file for debug data
    

    av.Run("JuanitaPie",{})
  end
end
'linFile.close 'close file for debug data

av.ClearMsg
av.ClearStatus
theView.GetGraphics.Invalidate