
using Oceananigans, JLD2, CairoMakie
using Statistics
using Printf

include("params.jl")

T_ts = FieldTimeSeries("ddc-T$(ΔT)-S$(ΔS).jld2", "T")
S_ts = FieldTimeSeries("ddc-T$(ΔT)-S$(ΔS).jld2", "S")

Tmax = maximum(abs, T_ts)
Smax = maximum(abs, S_ts)
Dmax = maximum(abs, -α .* interior(T_ts) .+ β .* interior(S_ts))

times = T_ts.times
xc = xnodes(T_ts[1])
zc = znodes(T_ts[1])

n = Observable(1)

Tn = @lift T_ts[$n]
Sn = @lift S_ts[$n]
Dn = @lift begin
    T = interior(T_ts[$n], :, 1, :)
    S = interior(S_ts[$n], :, 1, :)
    -α .* T .+ β .* S
end
Dprof = @lift vec(mean($Dn, dims = 1))

# layout
fig = Figure(size = (900, 900))

ax_T = Axis(fig[2, 2]; title = "Temperature perturbation")
ax_S = Axis(fig[2, 4]; title = "Salinity perturbation")
ax_D = Axis(fig[3, 2]; title = "Density perturbation")
hidedecorations!(ax_T)
hidedecorations!(ax_S)
hidedecorations!(ax_D)

ax_P = Axis(fig[3, 4]; title = "Horizontally-averaged density", xticks = LinearTicks(3))
hideydecorations!(ax_P)
xlims!(ax_P, -1.1 * Dmax, 1.1 * Dmax)
ylims!(ax_P, first(zc) - (zc[2]-zc[1])/2, last(zc) + (zc[2]-zc[1])/2)

title = @lift @sprintf("t=%1.2f [s]", times[$n])
fig[1, 1:4] = Label(fig, title, fontsize = 24, tellwidth = false)

hm_T = heatmap!(ax_T, Tn; colorrange = (-Tmax, Tmax), colormap = :coolwarm)
Colorbar(fig[2, 1], hm_T; flipaxis = false)

hm_S = heatmap!(ax_S, Sn; colorrange = (-Smax, Smax), colormap = :speed)
Colorbar(fig[2, 3], hm_S; flipaxis = false)

hm_D = heatmap!(ax_D, xc, zc, Dn; colorrange = (-Dmax, Dmax), colormap = :balance)
Colorbar(fig[3, 1], hm_D; flipaxis = false)

vlines!(ax_P, 0; color = :gray, linestyle = :dash)
lines!(ax_P, Dprof, zc; linewidth = 3, color = :black)

rowsize!(fig.layout, 2, Aspect(2, 1.0))
rowsize!(fig.layout, 3, Aspect(2, 1.0))
resize_to_layout!(fig)

fig

# Finally, we record a movie.

frames = 1:length(times)

@info "Making an animation..."

record(fig, "ddc-T$(ΔT)-S$(ΔS).mp4", frames, framerate=24) do i
#record(fig, "ddc-T$(ΔT)-S$(ΔS).gif", frames, framerate=24) do i
    n[] = i
end
nothing #hide


@info "Making frame snapshots..."

for i in 1:100:length(times)
    n[] = i
    save("ddc-T$(ΔT)-S$(ΔS)-n$(i).png", fig)
end
nothing #hide

