import json
import PySAM.Pvwattsv8 as pv
import PySAM.Grid as gr
import PySAM.Utilityrate5 as ur
import PySAM.Singleowner as so
import pandas as pd
import csv

def CT_SAM_Analysis():

    # modules required for the PVWatts - Single Owner configuration
    # see https://nrel-pysam.readthedocs.io/en/master/Configs.html

    system_model = pv.new()
    grid_model = gr.from_existing(system_model)
    rate_model = ur.from_existing(system_model)
    financial_model = so.from_existing(system_model)

    # list of modules in the correct execution order
    modules = [system_model, grid_model, rate_model, financial_model]

    # list of JSON input files exported from SAM for Case 1
    # see https://nrel-pysam.readthedocs.io/en/master/Import.html
    input_files = ['CT_SAM_Version1_pvwattsv8.json', 'CT_SAM_Version1_grid.json', 'CT_SAM_Version1_utilityrate5.json',
                   'CT_SAM_Version1_singleowner.json']

    # set the weather file
    weather_path = "C:/Users/adam.gallaher/SAM Downloaded Weather Files/%s" % weather_files[i]
    print (weather_path)
    system_model.SolarResource.solar_resource_file = weather_path

    # loop through the JSON input files to set inputs for all modules
    for f, m in zip(input_files, modules):
        with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/SAM/Version_1/' + f, 'r') as file:
            data = json.load(file)
            for k, v in data.items():
                if k != "number_inputs":
                    m.value(k, v)

    # run the modules in the correct order
    for m in modules:
        m.execute()

    annual_energy = system_model.Outputs.ac_annual
    Annual_Energy_Output.append(annual_energy)

    capacity_factor = system_model.Outputs.capacity_factor
    CF_Output.append(capacity_factor)

    lcoe = financial_model.Outputs.lcoe_real
    LEOC_Output.append(lcoe)


#########################################################################################################################
# Above is the function used to run SAM modeling analysis

kW_filename = open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/Results/Version_1/Parcel_Location_Analysis_BL.csv', 'r')
file = csv.DictReader(kW_filename)
Kw_list = []
weather_files = []
acres = []
Annual_Energy_Output = []
LEOC_Output = []
CF_Output = []
Lat = []
Long = []

i = 0
print (i)
for col in file:
    Kw_list.append(col['Total_kW'])
    weather_files.append(col['file_names'])
    acres.append(col['Parcel_Acres'])
    Lat.append(col['Parcel_Latitude'])
    Long.append(col['Parcel_Longitude'])
    # Change system size and weather file in JSON for SAM
    with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/SAM/Version_1/CT_SAM_Version1_pvwattsv8.json',
              'r') as f:
        json_data = json.load(f)
        json_data['system_capacity'] = float(Kw_list[i])
        json_data['solar_resource_file'] = "C:/Users/adam.gallaher/SAM Downloaded Weather Files/%s" % weather_files[i]

    with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/SAM/Version_1/CT_SAM_Version1_pvwattsv8.json',
              'w') as f:
        f.write(json.dumps(json_data))

    # Change land use for solar project in JSON file
    with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/SAM/Version_1/CT_SAM_Version1_singleowner.json',
              'r') as f:
        json_data = json.load(f)
        json_data['land_area'] = float(acres[i])

    with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/SAM/Version_1/CT_SAM_Version1_singleowner.json',
              'w') as f:
        f.write(json.dumps(json_data))

    CT_SAM_Analysis()
    i = i + 1

dictionary = {'Parcel Latitude': Lat, 'Parcel Longitude': Long, 'Capacity Factor': CF_Output, 'Annual Energy Output (kWh)': Annual_Energy_Output,
              'LCOE (cents/kWh)': LEOC_Output, 'weather_files': weather_files, 'Parcel Acres': acres, 'System Size (kW)': Kw_list}
dataframe = pd.DataFrame(dictionary)
dataframe.to_csv('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/SAM/Version_1/Results/CT_SAM_Output_BL.csv')


