"""
This contains old code for reading dates from xml files.  We are now using html files, but it may be worth keeping
this around for now.
"""
import os
import arcpy
from xml.dom import minidom
import xml.etree.ElementTree as ET



YEAR = 'year'
TILE = 'tile'
OUT_FNAME = 'tile_extents'
RAS_FOLDER = r'C:\GIS_Project\WBD\AK\Work\hu19080305\DEM_19080305'
if arcpy.env.workspace:
    POLYGON_FOLDER = arcpy.env.workspace
else:
    POLYGON_FOLDER = RAS_FOLDER

with arcpy.EnvManager(workspace=RAS_FOLDER):
    ras_list = arcpy.ListRasters()
    ras_list = [os.path.join(RAS_FOLDER, r) for r in ras_list if not r.startswith('dem')]

extent_polygons = []
for ras in ras_list:
    try:
        root = ET.parse(os.path.splitext(ras)[0] + '.xml').getroot()
        beg_year = [d.text for d in root.iter('begdate')][0][:4]
        end_year = [d.text for d in root.iter('enddate')][0][:4]
        if beg_year != end_year:
            year = beg_year + end_year
        else:
            year = beg_year
    except FileNotFoundError:
        year = ''
    print(year)
    
    with arcpy.EnvManager(overwriteOutput = True):
        tile_name = os.path.splitext(os.path.basename(ras))[0]
        polygon_fpath = os.path.join(POLYGON_FOLDER, tile_name)
        extent = arcpy.ddd.RasterDomain(ras, polygon_fpath, "POLYGON")
        arcpy.AddField_management(extent, field_name=YEAR, field_type='TEXT')
        arcpy.AddField_management(extent, field_name=TILE, field_type='TEXT')
        arcpy.CalculateField_management(extent, TILE, "'{}'".format(tile_name), 'PYTHON')
        arcpy.CalculateField_management(extent, YEAR, "'{}'".format(year), 'PYTHON')
        extent_polygons.append(extent)
with arcpy.EnvManager(overwriteOutput = True):
    arcpy.Merge_management(extent_polygons, os.path.join(RAS_FOLDER, OUT_FNAME))

for fc in extent_polygons:
    arcpy.Delete_management(fc)