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 = ['untitled_pvwattsv8_test.json', 'untitled_grid.json', 'untitled_utilityrate5.json',
                   'untitled_singleowner.json']

    # set the weather file
    weather_path = "C:/Users/adam.gallaher/SAM Downloaded Weather Files/%s" % weather_files[i]
    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_SAM_Analysis/Test_Analysis/' + 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()
    print('Annual Energy =', system_model.Outputs.ac_annual, '| NPV =', financial_model.Outputs.project_return_aftertax_npv, '| LCOE =', financial_model.Outputs.lcoe_real)


kW_filename = open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/Results/Version_1/Test.csv', 'r')
file = csv.DictReader(kW_filename)
Kw_list = []
weather_files = []
acres = []

i = 0
for col in file:
    Kw_list.append(col['Total_kW'])
    weather_files.append(col['file_names'])
    acres.append(col['Parcel_Acres'])
    #Solar_ID.append(col['Solar_ID'])
    with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_SAM_Analysis/Test_Analysis/untitled_pvwattsv8_test.json',
              'r') as f:
        json_data = json.load(f)
        json_data['system_capacity'] = float(Kw_list[i])

    with open('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_SAM_Analysis/Test_Analysis/untitled_pvwattsv8_test.json',
              'w') as f:
        f.write(json.dumps(json_data))
i = i + 1
CT_SAM_Analysis()
print('System Capacity (kW):', Kw_list)
print('weather file name:', weather_files)
print('Total parcel acres:', acres)



# capacity_factor_list = []
# annual_energy_list = []
# Example_PPA_list = []
# Levelized_cost_list = []
# lat_list = []
# lon_list = []

# j = 0





    # j = j + 1
    # capacity_factor = system_model.Outputs.capacity_factor
    # capacity_factor_list.append(capacity_factor)
    # print(capacity_factor)
    #
    # annual_energy = system_model.Outputs.annual_energy
    # annual_energy_list.append(annual_energy)
    # print(annual_energy)
    #
    # # Example_PPA = financial_model.Outputs.project_return_aftertax_npv
    # # Example_PPA_list.append(Example_PPA)
    # # print(Example_PPA)
    # #
    # # Levelized_cost = financial_model.Outputs.lcoe_real
    # # Levelized_cost_list.append(Levelized_cost)
    # # print(Levelized_cost)
    #
    # lat = system_model.Outputs.lat
    # lat_list.append(lat)
    # print(lat)
    #
    # long = system_model.Outputs.lon
    # lon_list.append(long)
    # print(long)
# display some results
#print('Annual Energy =', system_model.Outputs.ac_annual, '| NPV =', financial_model.Outputs.project_return_aftertax_npv, '| LCOE =', financial_model.Outputs.lcoe_real)



#dictionary = {'Capacity Factor': capacity_factor_list, 'Annual Energy Output (kWh)': annual_energy_list,
              #'Latitude': lat_list, 'Longitude': lon_list, 'weather_files': weather_files, 'Acres': acres, 'kW': Kw_list,}
#dataframe = pd.DataFrame(dictionary)
#dataframe.to_csv('C:/Dissertation/Chapter_1_SolarSiting/Data/CT_Data/Parcel_Analysis/Results/Version_1/Test_Output_4.csv')