import os
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# ----------------------------
# Settings
# ----------------------------
file_csv = 'greenfarm_temp.csv'
title_name = 'Greenville Farm Weather Station'
#file_csv = 'Venice_temp.csv'
#title_name = 'Venice Weather Station'

# ----------------------------
# Read CSV file
# ----------------------------
print(' ----- Read CSV file ------')

fin = pd.read_csv(
    file_csv,
    na_values=['M', 'T'],
    encoding='ISO-8859-1',
    delimiter=',',
    header=0,
    names=['date', 'temp']
)

# Convert timestamp to datetime
fin['date'] = pd.to_datetime(fin['date'])

# Convert temperature to numeric
fin['temp'] = pd.to_numeric(fin['temp'])

print(fin)
print(' ----------------------------')

# Show missing-value count
print(' ----- Missing value check ------')
print(fin.isna().sum())
print(' ----------------------------')

# ----------------------------
# Time and temperature setting
# ----------------------------
print(' ----- Time setting ------')
date = fin['date']
print(date)
print(' ----------------------------')

print(' ----- Temperature setting ------')
temp = xr.DataArray(fin['temp'], dims=('date',), coords={'date': date})
print(temp)
print(' ----------------------------')

# ----------------------------
# Plot
# ----------------------------
fig, ax = plt.subplots()

ax.plot(date, temp, 'o', markersize=2, color='C1')

ax.set_xlabel('Date')
ax.set_ylabel('Air Temperature [°F]')
ax.set_title(title_name)

ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(mdates.MonthLocator())

ax.grid(True)
fig.autofmt_xdate()

# ----------------------------
# Save figure using script name
# ----------------------------
script_name = os.path.splitext(os.path.basename(__file__))[0]
outfile = script_name + '.png'

plt.savefig(outfile)
print('Figure saved as:', outfile)

plt.show()

