import argparse
import configparser
import logging
import pathlib

import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np

parser = argparse.ArgumentParser(description="Animate swash output")
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("-c", "--config", default="config.ini")
args = parser.parse_args()

logging.basicConfig(level=max((10, 20 - 10 * args.verbose)))
log = logging.getLogger("post")

log.info("Starting post-processing")
config = configparser.ConfigParser()
config.read(args.config)

inp = pathlib.Path(config.get("post", "inp"))
root = pathlib.Path(config.get("swash", "out"))
out = pathlib.Path(config.get("post", "out"))
out.mkdir(parents=True, exist_ok=True)


def data(var):
    return np.load(inp.joinpath(f"{var}.npy"))


x = data("x")
t = data("t")

watl = data("watl")
botl = data("botl")

wl = np.maximum(watl, -botl)
# print(x.size, -np.arange(0, 1 * bathy.hstru.size, 1)[::-1].size)

fig, ax = plt.subplots()
ax.plot(x, -botl, c="k")
ax.set(xlim=(x.min(), x.max()), ylim=(-30, 10), xlabel="x (m)", ylabel="z (m)")
tit = ax.text(
    0.5,
    0,
    f"t={t[0]}",
    horizontalalignment="center",
    verticalalignment="bottom",
    transform=ax.transAxes,
)
ax.grid()
# ax.fill_between(
#    x, -botl, -data["botl"] + bathy.hstru, color="k", alpha=0.2
# )
(line,) = ax.plot(x, wl[0])


def animate(i):
    line.set_ydata(wl[i])
    tit.set_text(f"t={t[i]*1e-3:.2f}s")

    return (line, tit)


ani = animation.FuncAnimation(
    fig, animate, frames=wl[:, 0].size, interval=20, blit=True
)

ani.save(out.joinpath("anim.mp4"))
