"""
Script to convert a CSV to geodatabase feature class. Used to
periodically load automatically-generated spreadsheet data into an
ArcSDE database. When used with a web-based spreadsheet template
(containing "Long" and "Lat" fields) this allows spreadsheet users to
automatically generate updates for live maps.
"""

import arcpy
import os

#### SET THESE VARIABLES BEFORE RUNNING ####
working_dir = "" # path to working directory; should be local to script's machine
csv_name = "" # name of automatically-generated CSV
target_name = "" # name of target (SDE) feature class
gdb = "" # path to geodatabase -- can be an SDE connection string
prefix = "" # leave empty if using file geodatabase; otherwise give SDE table prefix string

arcpy.env.workspace = working_dir
arcpy.env.overwriteOutput = True

xy_table = csv_name
x_field = "Long"
y_field = "Lat"
spatial_ref = arcpy.SpatialReference()
spatial_ref.factoryCode = 4326 #WGS84
spatial_ref.create()

arcpy.MakeXYEventLayer_management(xy_table, x_field, y_field, "new", spatial_ref)

# check for existing feature class; 'archive' if present
arcpy.env.workspace = gdb
fclist = arcpy.ListFeatureClasses()

if "{prefix}{name}".format(prefix = prefix, name = target_name) in fclist:
    arcpy.CopyFeatures_management("{0}".format(target_name), "{0}_old".format(target_name))
    arcpy.Delete_management(target_name)

#arcpy.env.workspace = working_dir
arcpy.FeatureClassToFeatureClass_conversion("new", gdb, target_name)
