# using PVWatts-Battery – Commercial Owner

import json

# import each module being used
import PySAM.Pvwattsv8 as Pvwatts           # detailed PV system model
import PySAM.Battwatts as Battwatts         # simbple battery model
import PySAM.Grid as Grid                   # electric grid model
import PySAM.Utilityrate5 as UtilityRate    # retail electricity bill calculator
import PySAM.Cashloan as CashLoan

# plotting and saving
import matplotlib.pyplot as plt
import pandas as pd

# create new instance of the pvsamv1 module + use from_existing() for the 
# subsequent modules so that all of the compute modules share the same data.
pv = Pvwatts.new()
batt = Battwatts.from_existing(pv)
grid = Grid.from_existing(pv)
ur = UtilityRate.from_existing(pv)
cl = CashLoan.from_existing(pv)

# get the inputs from the JSON file from SAM desktop "PySAM JSON"
directory = r"C:\Users\Trinity\Desktop\Testing PySAM\Battwatts SAM PySAM JSON - ONE DAY" + "\\"
file_names = ["Battwatts_pvwattsv8","Battwatts_battwatts", "Battwatts_grid", "Battwatts_utilityrate5", "Battwatts_cashloan"]
modules = [pv, batt, grid, ur, cl]

# Loop through each module for inputs
for f, m in zip(file_names, modules):
    with open(directory + f + ".json", 'r') as file:
        data = json.load(file)
        # iterate through the input key-value pairs and set the module inputs
        for k, v in data.items():
            if k != "number_inputs":
                m.value(k, v)

# --- Override Time-Series Data for One-Day Simulation ---

# 1. Adapt Solar Resource Data
# Get the annual weather file path that was loaded from the JSON
solar_file = pv.SolarResource.solar_resource_file

weather_df = pd.read_csv(solar_file, skiprows=2)


#create the data dictionary for PySAM from the first 24 rows
solar_data_dict = {
    'lat': 33.45,
    'lon': -111.98,
    'tz': -7,
    'elev': 358,
    'dn': weather_df['DNI'].iloc[0:24].tolist(),
    'df': weather_df['DHI'].iloc[0:24].tolist(),
    'gh': weather_df['GHI'].iloc[0:24].tolist(),
    'wspd': weather_df['Wind Speed'].iloc[0:24].tolist(),
    'tdry': weather_df['Temperature'].iloc[0:24].tolist(),
}


# manually set solar resource data to ensure its using my 24 window
pv.SolarResource.solar_resource_data = {'0':'0'}
pv.SolarResource.solar_resource_data = solar_data_dict


# run each model in the correct order
i = 0
for m in modules:
    print('On module:', file_names[i])
    m.execute()
    print('Done module:', file_names[i])
    i += 1
    
#Results
directory = r"C:\Users\Trinity\Desktop\Testing PySAM\Battwatts-PySAMfiles - ONEDAY" + '\\'

current = pd.Series(batt.Outputs.batt_I[0:24])
current.to_csv(directory + 'Current.csv')

plt.plot(range(0,24,1), batt.Outputs.batt_SOC[0:24])
plt.xlabel('Hour of year')
plt.ylabel('Battery SOC (%)')
plt.savefig(directory + 'SOC.png')
plt.show()
