# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 11:54:11 2021

@author: <NAME>

Source (run) the script to load the functions, then call them from
the interactive prompt.
Assumes you have already sourced 'simulateOccurrence.py' and 'callAPI.py'.

"""

#from .. import getPest
import datetime as dt

def box(occs, rect):
  """
  Selects a set of occurrence record UIDs that lie within the rect. This allows you to
  update or delete records within a geographic area.

  Parameters:
    occs  list of APC occurrence records
    rect  tuple (topleftLat, topleftLong, bottomrightLat, bottomrightLong)
  Returns: a list of UIDs
  TODO: refactor to allow for northern hemisphere locations
  """
  intheBox = []   # empty list
  bounds = dict((('tlLat',rect[0]),('tlLong',rect[1]),('brLat',rect[2]),('brLong',rect[3])))
  for item in occs:
    point = dict((('lat', float(item['latitude'])),('long', float(item['longitude']))))
    if point['lat'] < bounds['tlLat']:
      if point['lat'] > bounds['brLat']:
        if point['long'] > bounds['tlLong']:
          if point['long'] < bounds['brLong']:
            intheBox.append(item['uid'])
  print('{0} records from {1} were in the box'.format(len(intheBox), len(occs)))
  return intheBox

#rect =  (-34, 124, -50, 136)  # bight all
#rect =  (-35.5, 125.5, -42.1, 132.5)  # bight
#rect =  (-34.65, 124.6, -39.1, 133.09)  # bight
#rect =  (-39.65, 128.3, -50.1, 135)  # bight
#rect =  (-32, 163, -39, 169)  # Tasman

# stress test
def spamPests(pestList=pestList, numOcc = 5, state='TASMAN'):
  """
  Loads sets of occurrence records for multiple species. It provides some records to
  look at or search, if few/none are already present.

  Parameters:
    pestList  List of pest names. This variable is automatically created if
              you source 'simulateOccurrence.py'
              If you want a subset of ALL the pests in the Program, subset
              pestList first and pass in the subset.
    numOcc    Number of occurrence records to create for each species.
    state     A code that is mapped to a location by getStateCentre()
              The default 'TASMAN' is an offshore area that allows testing without
              interfering with real records.

  """
  for i in range(len(pestList)):
    pest=getPest(i)
    data = createPayload(numOcc, state, pestID=i)
    for d in data:
      # d['status'] = 'Present'   # uncomment and edit to apply same status to all records
      d['eventID'] = 'spamPests:' + pest + '-' +str(i)
    print(i, pest, dt.datetime.now().strftime("%H:%M:%S%f"))
    uploadOcc(data)

def statusSummary(occs):
  """
  Takes a list of occurence records and prints a table with one row per pest
  showing the the pest name, the number of records with each status, and total occurrences.

  Parameter:
      occs    A list of occurrence records, each record being a dict with keys that match data spec.

  """
  # status stuff
  pests =  [item['entityName'] for item in occs]  # extract the pest name from all occurrences
  pestDistinct = sorted(list(set(pests)))   # List of pest names (not repeated)
  statuses=[item['status'] for item in occs]
  statusDistinct = list(set(statuses))
  tot=0
  for aPest in pestDistinct:
    # Create a list of occurrence records for the given pest
    aPestRec = [item for item in occs if item['entityName'] == aPest]
    # Now list all the statuses for the pest
    statuses=[item['status'] for item in aPestRec]
    statusDistinct = list(set(statuses))               # collect the distinct status values
    sCount= list(map(statuses.count, statusDistinct))  # apply the count method for each status value
    print(aPest, sCount, statusDistinct, sum(sCount))
    tot = tot + sum(sCount)
  print(tot)                                           # Gand total (== len(occs))


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 11:54:11 2021

@author: <NAME>

Source (run) the script to load the functions, then call them from
the interactive prompt.
Assumes you have already sourced 'simulateOccurrence.py' and 'callAPI.py'.

"""

#from .. import getPest
import datetime as dt

def box(occs, rect):
  """
  Selects a set of occurrence record UIDs that lie within the rect. This allows you to
  update or delete records within a geographic area.

  Parameters:
    occs  list of APC occurrence records
    rect  tuple (topleftLat, topleftLong, bottomrightLat, bottomrightLong)
  Returns: a list of UIDs
  TODO: refactor to allow for northern hemisphere locations
  """
  intheBox = []   # empty list
  bounds = dict((('tlLat',rect[0]),('tlLong',rect[1]),('brLat',rect[2]),('brLong',rect[3])))
  for item in occs:
    point = dict((('lat', float(item['latitude'])),('long', float(item['longitude']))))
    if point['lat'] < bounds['tlLat']:
      if point['lat'] > bounds['brLat']:
        if point['long'] > bounds['tlLong']:
          if point['long'] < bounds['brLong']:
            intheBox.append(item['uid'])
  print('{0} records from {1} were in the box'.format(len(intheBox), len(occs)))
  return intheBox

#rect =  (-34, 124, -50, 136)  # bight all
#rect =  (-35.5, 125.5, -42.1, 132.5)  # bight
#rect =  (-34.65, 124.6, -39.1, 133.09)  # bight
#rect =  (-39.65, 128.3, -50.1, 135)  # bight
#rect =  (-32, 163, -39, 169)  # Tasman

# stress test
def spamPests(pestList=pestList, numOcc = 5, state='TASMAN'):
  """
  Loads sets of occurrence records for multiple species. It provides some records to
  look at or search, if few/none are already present.

  Parameters:
    pestList  List of pest names. This variable is automatically created if
              you source 'simulateOccurrence.py'
              If you want a subset of ALL the pests in the Program, subset
              pestList first and pass in the subset.
    numOcc    Number of occurrence records to create for each species.
    state     A code that is mapped to a location by getStateCentre()
              The default 'TASMAN' is an offshore area that allows testing without
              interfering with real records.

  """
  for i in range(len(pestList)):
    pest=getPest(i)
    data = createPayload(numOcc, state, pestID=i)
    for d in data:
      # d['status'] = 'Present'   # uncomment and edit to apply same status to all records
      d['eventID'] = 'spamPests:' + pest + '-' +str(i)
    print(i, pest, dt.datetime.now().strftime("%H:%M:%S%f"))
    uploadOcc(data)

def statusSummary(occs):
  """
  Takes a list of occurence records and prints a table with one row per pest
  showing the the pest name, the number of records with each status, and total occurrences.

  Parameter:
      occs    A list of occurrence records, each record being a dict with keys that match data spec.

  """
  # status stuff
  pests =  [item['entityName'] for item in occs]  # extract the pest name from all occurrences
  pestDistinct = sorted(list(set(pests)))   # List of pest names (not repeated)
  statuses=[item['status'] for item in occs]
  statusDistinct = list(set(statuses))
  tot=0
  for aPest in pestDistinct:
    # Create a list of occurrence records for the given pest
    aPestRec = [item for item in occs if item['entityName'] == aPest]
    # Now list all the statuses for the pest
    statuses=[item['status'] for item in aPestRec]
    statusDistinct = list(set(statuses))               # collect the distinct status values
    sCount= list(map(statuses.count, statusDistinct))  # apply the count method for each status value
    print(aPest, sCount, statusDistinct, sum(sCount))
    tot = tot + sum(sCount)
  print(tot)                                           # Gand total (== len(occs))


# -*- coding: utf-8 -*- Created on Wed Apr 28 11:54:11 2021  @author: <NAME>  Source (run) the script to load the functions, then call them from the interactive prompt. Assumes you have already sourced 'simulateOccurrence.py' and 'callAPI.py'. #from .. import getPest Selects a set of occurrence record UIDs that lie within the rect. This allows you to   update or delete records within a geographic area.    Parameters:     occs  list of APC occurrence records     rect  tuple (topleftLat, topleftLong, bottomrightLat, bottomrightLong)   Returns: a list of UIDs   TODO: refactor to allow for northern hemisphere locations # empty list #rect =  (-34, 124, -50, 136)  # bight all #rect =  (-35.5, 125.5, -42.1, 132.5)  # bight #rect =  (-34.65, 124.6, -39.1, 133.09)  # bight #rect =  (-39.65, 128.3, -50.1, 135)  # bight #rect =  (-32, 163, -39, 169)  # Tasman # stress test Loads sets of occurrence records for multiple species. It provides some records to   look at or search, if few/none are already present.    Parameters:     pestList  List of pest names. This variable is automatically created if               you source 'simulateOccurrence.py'               If you want a subset of ALL the pests in the Program, subset               pestList first and pass in the subset.     numOcc    Number of occurrence records to create for each species.     state     A code that is mapped to a location by getStateCentre()               The default 'TASMAN' is an offshore area that allows testing without               interfering with real records. # d['status'] = 'Present'   # uncomment and edit to apply same status to all records Takes a list of occurence records and prints a table with one row per pest   showing the the pest name, the number of records with each status, and total occurrences.    Parameter:       occs    A list of occurrence records, each record being a dict with keys that match data spec. # status stuff # extract the pest name from all occurrences # List of pest names (not repeated) # Create a list of occurrence records for the given pest # Now list all the statuses for the pest # collect the distinct status values # apply the count method for each status value # Gand total (== len(occs))