using Oceananigans
using JLD2
using Printf

include("params.jl")

Pr = ν / κT
Sc = ν / κS
Le = Sc / Pr
Rρ = α*ΔT / (β*ΔS)
Ra = g * α * ΔT * H^3 / (ν * κT)

println("Pr=$Pr  Sc=$Sc  Le=$Le  Rρ=$Rρ  Ra=$Ra")

# define grid
Nx = Nz = 256
grid = RectilinearGrid(CPU(); size = (Nx, Nz), x = (0, H), z = (-H/2, H/2),
                       topology = (Periodic, Flat, Bounded))

# define buoyancy
buoyancy = SeawaterBuoyancy(
    gravitational_acceleration = g,
    equation_of_state = LinearEquationOfState(thermal_expansion = α,
                                              haline_contraction = β))

# define boundary condition
u_bcs = FieldBoundaryConditions(bottom = ValueBoundaryCondition(0),
                                top    = ValueBoundaryCondition(0))

# define model
model = NonhydrostaticModel(grid;
            buoyancy,
            tracers = (:T, :S),
            closure = ScalarDiffusivity(ν = ν, κ = (T = κT, S = κS)),
            advection = WENO(),
            boundary_conditions = (u = u_bcs,))

# define initial condition
ε = 1e-3
Tᵢ(x, z) = 0.5*ΔT*tanh(z/(H/20)) + ε * ΔT * randn()
Sᵢ(x, z) = 0.5*ΔS*tanh(z/(H/20)) + ε * ΔS * randn()
set!(model, T = Tᵢ, S = Sᵢ)

# configure simulation
simulation = Simulation(model; Δt = 1e-5, stop_time = 100)
conjure_time_step_wizard!(simulation, IterationInterval(10);
                          cfl = 0.5, diffusive_cfl = 0.1, max_Δt = 1e-0)

function progress(sim)
    w = sim.model.velocities.w
    @info @sprintf("iter %06d, t = %.3f, Δt = %.2e, max|w| = %.3e",
                   iteration(sim), time(sim), sim.Δt, maximum(abs, w))
end
add_callback!(simulation, progress, IterationInterval(500))

# output result
T, S = model.tracers
outputs = (T = T, S = S,
           T̄ = Average(T, dims = 1),
           S̄ = Average(S, dims = 1))

simulation.output_writers[:fields] = JLD2Writer(model, outputs;
    filename = "ddc-T$(ΔT)-S$(ΔS).jld2",
    schedule = TimeInterval(0.1),
    overwrite_files = true)

# execute simulation
run!(simulation)

