﻿using System;
using APIclient_Csharp;

namespace ApiClientCsharp
{
    internal class Program
    {
        static void Main()
        {
            // Pipe cross-section parameters
            // ======================================================================================================================================
            var D_hydro = 0.4033; // Hydrodynamic pipe diameter
            var D = 0.4033; // Outer pipe diameter
            var w_s = 484.76; // Submerged pipe weight per unit length
            var w_s_installation = 1100.0; // Submerged pipe weight per unit length during installation
            var w_s_waterfilled = 484.76; // Submerged pipe weight per unit length in waterfilled condition
            var m = 180.74; // Dry pipe mass per unit length
            var k = 0.0; // Dummy parameter. Set to: 0.0
            var t_mgrt = 0.0; // Thickness of marine growth
            var k_lay_user = 1.0; // User defined lay factor
            var EI = 0.0; // Bending stiffness of pipe
            var T0 = 0.0; // Horizontal component of effective lay tension
            var alpha_m = 0.0; // Damping coefficient for mass-proportional Rayleigh damping

            var inCross_real = new double[12] { D_hydro, D, w_s, w_s_installation, w_s_waterfilled, m, k, t_mgrt, k_lay_user, EI, T0, alpha_m };

            // Hydrodynamic variables
            // ======================================================================================================================================
            var rho_w = 1028.0; // Water density
            var U_m = 0.61; // Flow velocity amplitude. Only used for regular waves
            var T = 10.0; // Regular-wave period
            var U_c = 0.358; // Steady current velocity perpendicular to pipe. Reductions due to boundary layer effect and directionality must be included by user
            var Phi_t = 110.0; // Phase displacement of regular wave
            var FH_m = 3000.0; // Horizontal force amplitude. Only used if a horizontal sine force is applied
            var T_FH = 10.0; // Horizontal force period. Only used if a horizontal sine force is applied
            var depth = 108.0; // Water depth
            double Tsimulation = 10800; // Simulation length. Include Tramp if ramping is activated
            var WaveVelRefHeight = 0.20165; // Reference height for generation of wave-induced water particle velocity.
            var Hs = 14.30; // Significant wave height for design sea state
            var Tp = 15.80; // Peak period for design spectrum
            var SpectrumPeakedness = 3.30; // Peak-enhancement factor for design spectrum
            var theta_w = 90.0; // Relative angle between pipe and wave heading
            var n_spreading = 8.0; // Spectral spreading exponent
            var r_H = 1.0; // Dummy parameter. Set to: 1.0
            var r_L = 1.0; // Reduction factor on hydrodynamic lift load
            var HydroModel = 4; // Force model option: 4 - Database force model, 5 - Horizontal sine force
            var flowtype = 0; // Not in use. Set to: 0
            var roughness = 2; // Pipe surface roguhness: 1 - Smooth, 2 - Rough, 3 - Very rough (roughness = 3 only applicable for HydroModel = 4)
            var GenerateRegularWave = 2; // A regular wave signal should be generated: 1 - True, 2 – False
            var SmoothWaveVelocity = 2; // Wake velocity should be smoothed prior to differentiation: 1 - True, 2 – False. Default value: 2
            var WaveOrder = 1; // Wave order option: 1 - Linear, 2 - Second order
            var SpectrumSpecification = 1; // Applicable Wave spectrum: 1 - JONSWAP
            var numseeds = 5; // Number of random seastates to be analysed
            var HydrodynamicDiameter_int = 2; // Option for specifying user defined hydrodynamic diameter: 1 – True, 2 – False
            var IncludeLiftReduction_int = 2; // Option for including reduction factor on hydrodynamic lift: 1 – True, 2 – False

            var inHydro_real = new double[17]
            {
                rho_w, U_m, T, U_c, Phi_t, FH_m, T_FH, depth, Tsimulation, WaveVelRefHeight, Hs, Tp, SpectrumPeakedness,
                theta_w, n_spreading, r_H, r_L
            };
            var inHydro_int = new int[10]
            {
                HydroModel, flowtype, roughness, GenerateRegularWave, SmoothWaveVelocity, WaveOrder,
                SpectrumSpecification, numseeds, HydrodynamicDiameter_int, IncludeLiftReduction_int
            };
            var seedArray_phase = new int[5] { 81663, 2142, 56225, 24849, 29681 };
            var seedArray_crest = new int[5] { 36657, 36657, 36657, 36657, 36657 };

            // Soil variables
            // ======================================================================================================================================
            var k_soil = 65000.0; // Elastic stiffness of the soil. Recommended value is 65000 N/m/m
            var mu = 0.6; // Friction coefficient. Specified by user for Coulomb friction. Set to 0.6 for sand and 0.2 for clay
            var gamma_mark = 10212.0; // Submerged (effective) unit weight of soil
            var rho_su = 0.0; // Depth gradient of undrained shear strength. Only used for SAFEBUCK and Geotechnical clay models
            var Nc = 5.0; // Bearing capacity factor for clay. Only used for initial penetration according to the Geotechnical clay model
            var su_z0 = 2000.0; // Undrained shear strength of soil at seabed (z = 0). Only used for SAFEBUCK and Geotechnical clay models
            var delta_mobilization = 0.0; // Mobilization distance required to reach failure at the relevant penetration depth. Expressed as fraction of the pipe-soil contact width B, which is calculated by the program. Only used for initial penetration calculations according to the SAFEBUCK and Geotechnical clay models
            var St = 1.0; // Sensitivity (ratio of intact to remoulded shear strength). Only used for SAFEBUCK and Geotechnical clay models when remoulded soil is considered
            var alpha_soil = 0.02; // Damping coefficient for soil damping in elastic regime (c_soil = alpha_soil * k_soil)
            var su_sigmav_NC = 0.5; // Ratio of the normally consolidated shear resistance to the consolidation normal stress. Typical range is between 0.25 and 0.5. Only used for Geotechnical clay model
            var alpha_brk = 1.1; // Pipe-soil adhesion factor. Only used for Geotechnical clay model
            var gamma_pre = 1.5; // Consolidation preloading effect. Taken as the ratio of preloading (e.g. waterfilled submerged weight) to the submerged weight in the condition considered. Only used for Geotechnical clay model
            var m_OCR = 0.8; // Exponent accounting for long-term effect of overconsolidation. Only used for Geotechnical clay model
            var kappa_active = 0.0; // Active earth pressure coefficient. A value of 2 is recommended to account for inclined loading (horizontal + lift). Only used for Geotechnical clay model when suction is included
            var kappa_passive = 2.5; // Passive earth pressure coefficient. A value of 2 is recommended to account for inclined loading (horizontal + lift). Only used for Geotechnical clay model
            var su_active = 0.0; // Average undrained shear strength within the active failure zone. Only used for Geotechnical clay model when suction is included
            var su_passive = 2000.0; // Average undrained shear strength within the passive failure zone. Only used for Geotechnical clay model
            var gamma_total = 18000.0; // Total unit soil weight in air. Only used for clay (in Verley and Lund model and after break-out in the other models). Verley and Lund recommend a value of 18000 N/m3 regardless of the value of submerged unit weight.
            var su = 2000.0; // Undrained shear strength of soil. Only used for Verley and Lund clay model
            var z_ini_user = 0.0; // User defined initial penetration
            var z_t = 0.0; // Trench depth
            var theta_t = 0.0; // Trench-wall angle
            var SoilModel = 2; // Soil model option: 1 - Coulomb friction, 2 - Pipe-sand, 3 - Pipe-clay
            var CalculatedLayFactor_int = 2; // Option for including a lay factor calculated by PILSS to increase static contact pressure for initial penetration calculation. 1 - True, 2 – False
            var UserDefinedLayFactor_int = 2; // Option for including a user defined lay factor to increase static contact pressure for initial penetration calculation. 1 – True, 2 – False
            var InitialPenetrationModel = 1; // Penetration calculation model option for pipe-clay: 1 - Verley and Lund (1995), 2 - SAFEBUCK, 3 - Geotechnical model
            var remoulded_int = 2; // Option for reducing shear strength due to remoulded soil (used for the combination SoilModel = 3 and InitialPenetrationModel = 2 or 3). 1 - True, 2 – False
            var suction_int = 2; // Option to account for clay suction: 1 - True, 2 – False
            var waterFilled_int = 2; // Option to account for weight of water-filled pipe when calculating initial penetration: 1 – True, 2 - False
            var UserDefinedInitialPenetration_int = 2; // Option to include user defined initial penetration: 1 – True, 2 - False
            var IncludeTrench_int = 2; // Option to include reduction factors on hydrodynamic loads due to trench. 1 – True, 2 - False

            var inSoil_real = new double[22]
            {
                k_soil, mu, gamma_mark, rho_su, Nc, su_z0, delta_mobilization, St, alpha_soil, su_sigmav_NC, alpha_brk,
                gamma_pre, m_OCR, kappa_active, kappa_passive, su_active, su_passive, gamma_total, su, z_ini_user, z_t,
                theta_t
            };
            var inSoil_int = new int[9]
            {
                SoilModel, CalculatedLayFactor_int, UserDefinedLayFactor_int, InitialPenetrationModel, remoulded_int,
                suction_int, waterFilled_int, UserDefinedInitialPenetration_int, IncludeTrench_int
            };

            // Timeseries variables
            // ======================================================================================================================================
            var t_start = 0.0; // Start time for dynamic analysis. Set to: 0.0
            var delta_t = 0.01; // Timestep for dynamic analysis. Typical timestep size is 0.001s
            var delta_t_signal = 0.35; // Timestep for wave-induced particle velocity signal. Recommended value is 0.35 s. Cannot be less than Δt
            var delta_t_res = 1.0; // Resolution of results vectors used for plots and writing results to file.
            var delta_t_plot = 1.0; // Resolution of plot vectors

            var inTime_real = new double[4] { t_start, delta_t, delta_t_signal, delta_t_res };
            var inTime_int = new int[1] { 0 }; // Not in use. Set to: 0

            // Dynamic solution variables
            // ======================================================================================================================================
            var RampUpPeriod = 0.0; // Duration of ramp-up period. Hydrodynamic loads increase linearly from zero to full strength during ramp-up period. Recommended duration is approximately 20% of the storm duration, or 2000 s for a three-hour storm
            var MaxNrOfIterations = 10; // Maximum number of equilibrium iterations in each timestep
            var RampUp_int = 2; // Set to 1 if storm ramp up introduces a linear reduction to hydrodynamic loads for the ramp-up period: 1 – True, 2 – False

            var inDyn_real = new double[1] { RampUpPeriod };
            var inDyn_int = new int[2] { MaxNrOfIterations, RampUp_int };

            // Time steps
            // ======================================================================================================================================
            var NrOfTimesteps = (int)(Math.Ceiling(Tsimulation / delta_t) + 1);
            var NrOfTimesteps_signal = (int)(Math.Ceiling(Tsimulation / delta_t_signal) + 1);
            var NrOfTimesteps_res = (int)(Math.Ceiling(Tsimulation / delta_t_res) + 1);
            var NrOfPlotsteps = (int)(Math.Ceiling(Tsimulation / delta_t_plot) + 1);

            // Results
            // ======================================================================================================================================
            var t_vector_U = new double[NrOfTimesteps_signal];
            // Pre-populating t_vector_U is kept for backwards compatibility. TODO: Remove in future version.
            // Since V2.2.0, PILSS pre-populates t_vector_U automatically (and over-writes existing values)
            if (GenerateRegularWave == 1 || HydroModel == 5)
            {
                for (int i = 0; i < t_vector_U.Length; i++)
                {
                    // The analyses assumes everything is zero at t=0 and start calculations on t = delta_t and t_signal = delta_t_signal
                    t_vector_U[i] = t_start + (i - 1) * delta_t_signal + delta_t_signal;
                }
            }
            var U_t_matrix = new double[numseeds, NrOfTimesteps_signal];
            var A_t_matrix = new double[numseeds, NrOfTimesteps_signal];
            var F_H_matrix = new double[numseeds, NrOfTimesteps_signal];
            var F_L_matrix = new double[numseeds, NrOfTimesteps_signal];
            var result_matrix = new double[6, 2];
            var maxMatrix = new double[numseeds, 10];
            var minMatrix = new double[numseeds, 10];
            var maxAbsMatrix = new double[numseeds, 10];

            // Plot
            // ======================================================================================================================================
            int addedPlotRows;
            if (Tsimulation / delta_t_plot % 1 == 0)
                addedPlotRows = 0;
            else
                addedPlotRows = 1;

            var dummyInteger = 1;
            var printToFile = 2; // 1 - Print all results to .txt file, 2 - Do not print results to file, 3 - Only print ResultsOverview to file
            var readWaveVelFromFile = 2;
            var generatePlots = true;
            var ExplicitAcceleration = true;
            var dummyBoolean = false;
            var dummyBoolean2 = true;

            var t_matrix_plot = new double[1, NrOfPlotsteps];
            var y_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var z_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var v_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var a_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var Fsoil_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var Fstiff_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var FHrel_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var FLrel_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var yref_matrix_plot = new double[numseeds, NrOfPlotsteps];
            var iElPl_matrix_plot = new int[numseeds, NrOfPlotsteps];
            var outvar_int_matrix = new int[numseeds, 5];

            const int MaxCharLength = 4096;
            string sResultsPath = "Results";
            string sCaseName = "CaseName";
            char[] resultsPath = sResultsPath.PadRight(MaxCharLength).ToCharArray();
            char[] caseName = sCaseName.PadRight(MaxCharLength).ToCharArray();
            // If using alternative way of defining interoperable strings:
            //var resultsPath = resultsPath1.PadRight(MaxCharLength);
            //var caseName = caseName1.PadRight(MaxCharLength);


            // Set to true of using the legacy v1.2 PILSS API
            const bool legacyApi = false;

            // Call API to PILSS
            Console.WriteLine($"Calling '{PilssFortranInterfaceDefinitions.pilssDllPathFullOrRelative}' from C# client: \n\r\n\r");
            if (legacyApi)
            {
                PilssFortranInterfaceDefinitions.PILSSInterface(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest, inSoil_real,
                    inSoil_int,
                    inTime_real, inTime_int, ref NrOfTimesteps, ref NrOfTimesteps_signal, ref NrOfTimesteps_res, inDyn_real,
                    inDyn_int, t_vector_U, U_t_matrix, A_t_matrix, F_H_matrix, F_L_matrix, ref NrOfPlotsteps,
                    ref addedPlotRows,
                    ref delta_t_plot, ref dummyInteger, ref printToFile, ref readWaveVelFromFile, ref generatePlots,
                    ref ExplicitAcceleration, ref dummyBoolean,
                    ref dummyBoolean2, result_matrix, maxMatrix, minMatrix, maxAbsMatrix, t_matrix_plot, y_matrix_plot,
                    z_matrix_plot,
                    v_matrix_plot, a_matrix_plot, Fsoil_matrix_plot, Fstiff_matrix_plot, FHrel_matrix_plot,
                    FLrel_matrix_plot,
                    yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix);
            }
            else
            {
                PilssFortranInterfaceDefinitions.PILSSInterface_v2(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest, inSoil_real,
                    inSoil_int,
                    inTime_real, inTime_int, ref NrOfTimesteps, ref NrOfTimesteps_signal, ref NrOfTimesteps_res, inDyn_real,
                    inDyn_int, t_vector_U, U_t_matrix, A_t_matrix, F_H_matrix, F_L_matrix, ref NrOfPlotsteps,
                    ref addedPlotRows,
                    ref delta_t_plot, ref dummyInteger, ref printToFile, ref readWaveVelFromFile, ref generatePlots,
                    ref ExplicitAcceleration, ref dummyBoolean,
                    ref dummyBoolean2, result_matrix, maxMatrix, minMatrix, maxAbsMatrix, t_matrix_plot, y_matrix_plot,
                    z_matrix_plot,
                    v_matrix_plot, a_matrix_plot, Fsoil_matrix_plot, Fstiff_matrix_plot, FHrel_matrix_plot,
                    FLrel_matrix_plot,
                    yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix, resultsPath: resultsPath, caseName: caseName);
            }
        }
    }
}