### Tests for each OPF objective ###

@testset "mincost objective" begin
    base_data = "data/case14/base"
    result = VariableFrequencyOPF.multifrequency_opf(base_data, "mincost", output_to_files=false)
    @test result[1]["status"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(result[1]["cost"][1], 8081.5; atol = 1e0)

    variablef_data = "data/case14_twoarea/two_area/"
    result = VariableFrequencyOPF.multifrequency_opf(variablef_data, "mincost", output_to_files=false)
    @test result[1]["status"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(result[1]["cost"][1], 7565.2; atol = 1e0)
    @test isapprox(result[1]["cost"][2], 553.6; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][1], 1.0; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][2], 60.0; atol = 1e0)

    base_data = "data/case14/base"
    result = VariableFrequencyOPF.multifrequency_opf(base_data, "mincost", output_to_files=true)
    result_output_dict = JSON.parsefile("results/case14/base/output_values.json")
    @test result_output_dict["status"] == "LOCALLY_SOLVED"
    @test isapprox(result_output_dict["cost"][1], 8081.5; atol = 1e0)
    try
        rm("results",force=true,recursive=true)
    catch IOError
        println("Unable to delete the results files generated by this test.")
    end
end

@testset "mincost objective_regularized" begin
    variablef_data = "data/case14_twoarea/two_area/"
    result = VariableFrequencyOPF.multifrequency_opf(variablef_data, "mincost", output_to_files=false, regularize_f=1e-4)
    @test result[1]["status"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(result[1]["cost"][1], 7565.2; atol = 1e0)
    @test isapprox(result[1]["cost"][2], 553.6; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][1], 1.0; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][2], 60.0; atol = 1e0)

    variablef_data = "data/case14_twoarea/two_area/"
    result = VariableFrequencyOPF.multifrequency_opf(variablef_data, "mincost", output_to_files=false, regularize_f=1e-2)
    @test result[1]["status"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(result[1]["cost"][1], 7565.2; atol = 1e0)
    @test isapprox(result[1]["cost"][2], 553.6; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][1], 1.0; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][2], 60.0; atol = 1e0)

    variablef_data = "data/case14_twoarea/two_area/"
    result = VariableFrequencyOPF.multifrequency_opf(variablef_data, "mincost", output_to_files=false, regularize_f=1e0)
    @test result[1]["status"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(result[1]["cost"][1], 7565.2; atol = 1e0)
    @test isapprox(result[1]["cost"][2], 553.6; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][1], 1.0; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][2], 60.0; atol = 1e0)

    variablef_data = "data/case14_twoarea/two_area/"
    result = VariableFrequencyOPF.multifrequency_opf(variablef_data, "mincost", output_to_files=false, regularize_f=1e3)
    @test result[1]["status"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(result[1]["cost"][1], 7345.4; atol = 1e0)
    @test isapprox(result[1]["cost"][2], 825.7; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][1], 60.0; atol = 1e0)
    @test isapprox(result[1]["frequency (Hz)"][2], 60.0; atol = 1e0)

    try
        rm("results",force=true,recursive=true)
    catch IOError
        println("Unable to delete the results files generated by this test.")
    end
end

@testset "areagen objective" begin
    original_network = "data/nordic_fault/base/fault_4032_4044.m"
    # We choose to put the new network data in the same folder because
    # we also want to use some data that is already there. Each upgrade
    # gets its own folder.
    new_data_directory = "results/inputs/nordic_fault/"
    standard_frequency = 50.0
    lfac_branch_upgrades = [27,33]

    VariableFrequencyOPF.upgrade_branches(
        original_network,
        new_data_directory,
        standard_frequency,
        indices=lfac_branch_upgrades
    )

    # Minimize generation in areas 2 and 3 with plots including
    # the power flow between areas 1 and 2
    objective = "areagen"
    gen_areas = [2,3]
    area_transfer = [1,2]
    # We want to plot the results of all branch upgrades,
    # so we set `enum_branch` to true
    enum_branches = true

    solution =  VariableFrequencyOPF.run_series(
        new_data_directory,
        objective;
        gen_areas=gen_areas,
        area_transfer=area_transfer,
        enum_branches=enum_branches
    )
    results_dict = solution[1]
    n_subnets = solution[2]
    subnet_array = solution[3]
    idx_sorted = solution[4]
    series_output_folder = solution[5]
    plot_best_x = solution[6]

    subnet1 = findall(results_dict["subnet"]["br27"].==1)[1]
    subnet2 = 3-subnet1

    @test results_dict["status"]["br27"] == MathOptInterface.LOCALLY_SOLVED
    @test results_dict["status"]["br33"] == MathOptInterface.LOCALLY_SOLVED
    @test isapprox(results_dict["cost"]["br27"][subnet1], 4.40154e6; rtol = 1e-2)
    @test isapprox(results_dict["cost"]["br27"][subnet2], 0.0; rtol = 1e-2)
    @test isapprox(results_dict["frequency (Hz)"]["br27"][subnet1], 50.0; atol = 1e0)
    # @test isapprox(results_dict["frequency (Hz)"]["br27"][subnet2], 20.92; atol = 1e0)
    @test isapprox(results_dict["cost"]["br33"][subnet1], 4.36446e6; rtol = 1e-2)
    @test isapprox(results_dict["cost"]["br33"][subnet2], 0.0; rtol = 1e-2)
    @test isapprox(results_dict["frequency (Hz)"]["br33"][subnet1], 50.0; atol = 1e0)
    # @test isapprox(results_dict["frequency (Hz)"]["br33"][subnet2], 22.43; atol = 1e0)

    results_dict_allplots = [results_dict]

    plot_output_folder = "results/nordic_fault/"
    series_labels = ["LFAC upgrades"]

    # VariableFrequencyOPF.plot_results_dicts_bar(
    #     results_dict_allplots,
    #     n_subnets,
    #     subnet_array,
    #     idx_sorted,
    #     plot_output_folder,
    #     plot_best_x,
    #     series_labels,
    #     color_palette=:Dark2_8
    # )
    #
    # @test isfile("results/nordic_fault/plots/total/total generation.pdf")
    # @test isfile("results/nordic_fault/plots/subnet1/subnet 1 line loss.pdf")
    # @test isfile("results/nordic_fault/plots/subnet2/subnet 2 frequency (Hz).pdf")

    try
        rm("results",force=true,recursive=true)
    catch IOError
        println("Unable to delete the results files generated by this test.")
    end
end

# @testset "frequency sweep" begin
#     original_network = "data/nordic_fault/base/fault_4032_4044.m"
#     # We choose to put the new network data in the same folder because
#     # we also want to use some data that is already there. Each upgrade
#     # gets its own folder.
#     new_data_directory = "results/inputs/nordic_fault/"
#     standard_frequency = 50.0
#     lfac_branch_upgrades = [27]
#     new_data_file = new_data_directory*"/br27"
#
#     VariableFrequencyOPF.upgrade_branches(
#         original_network,
#         new_data_directory,
#         standard_frequency,
#         indices=lfac_branch_upgrades
#     )
#
#     # Minimize generation in areas 2 and 3 with plots including
#     # the power flow between areas 1 and 2
#     objective = "areagen"
#     fmin = 0:10:30
#     fmax = 0:10:30
#     results_dicts = Array{Dict}(undef, 1)
#     output_plots = Array{Any}(undef, 1)
#     (results_dicts[1], output_plots[1]) = VariableFrequencyOPF.frequency_ranges(
#         fmin,
#         fmax,
#         2,
#         new_data_file,
#         objective,
#         [("frequency (Hz)",2)],
#         [
#         ("nw",2,"branch",1,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",2,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",3,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",4,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",5,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",5,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",6,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",7,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",8,["pt","pf","qt","qf"])
#         ];
#         gen_areas=[2,3],
#         area_transfer=[1,2],
#         no_converter_loss=true
#     )
#
#     @test isfile("results/results/nordic_fault/br27/plots/vs subnet 2 frequency (Hz)/total/total generation in areas 2 and 3 (p.u.) vs subnet 2 frequency (Hz).pdf")
#     @test isfile("results/results/nordic_fault/br27/plots/vs subnet 2 frequency (Hz)/subnet1/subnet 1 line loss vs subnet 2 frequency (Hz).pdf")
#     @test isfile("results/results/nordic_fault/br27/plots/vs subnet 2 frequency (Hz)/subnet2/subnet 2 converter loss vs subnet 2 frequency (Hz).pdf")
#     @test isfile("results/nordic_fault/multiterminal_sweep/plots/vs subnet 2 frequency (Hz)/nw/2/branch/1/nw 2 branch 1 pf vs subnet 2 frequency (Hz).pdf")
#
#     # Now test the direct application of a data dictionary
#     output_results_folder = "time_0"
#     mn_data = VariableFrequencyOPF.read_sn_data(new_data_file, no_converter_loss=false)
#
#     folder = abspath(new_data_file)
#     folder_split = splitpath(folder)
#     toplevels = folder_split[1:end-3]
#     output_folder = joinpath(toplevels...,"results/$(folder_split[end-1])/$(folder_split[end])")
#     output_folder = joinpath(output_folder, output_results_folder)
#     if !isdir(output_folder)
#         mkpath(output_folder)
#     end
#
#     (results_dicts[1], output_plots[1]) = VariableFrequencyOPF.frequency_ranges(
#         fmin,
#         fmax,
#         2,
#         mn_data,
#         output_folder,
#         objective,
#         [("frequency (Hz)",2)],
#         [
#         ("nw",2,"branch",1,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",2,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",3,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",4,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",5,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",5,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",6,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",7,["pt","pf","qt","qf"]),
#         ("nw",2,"branch",8,["pt","pf","qt","qf"])
#         ];
#         gen_areas=[2,3],
#         area_transfer=[1,2]
#     )
#     @test isfile("results/results/nordic_fault/br27/time_0/plots/vs subnet 2 frequency (Hz)/total/total generation in areas 2 and 3 (p.u.) vs subnet 2 frequency (Hz).pdf")
#     @test isfile("results/results/nordic_fault/br27/time_0/plots/vs subnet 2 frequency (Hz)/subnet1/subnet 1 line loss vs subnet 2 frequency (Hz).pdf")
#     @test isfile("results/results/nordic_fault/br27/time_0/plots/vs subnet 2 frequency (Hz)/subnet2/subnet 2 converter loss vs subnet 2 frequency (Hz).pdf")
#
#     try
#         rm("results",force=true,recursive=true)
#     catch IOError
#         println("Unable to delete the results files generated by this test.")
#     end
# end
