import argparse
import configparser
import logging
import pathlib

import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as sgl

parser = argparse.ArgumentParser(description="Post-process 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"))

log.info(f"Reading data from '{inp}'")
x = np.load(inp.joinpath("x.npy"))
t = np.load(inp.joinpath("t.npy"))

botl = np.load(inp.joinpath("botl.npy"))
watl = np.load(inp.joinpath("watl.npy"))
vel = np.load(inp.joinpath("vel.npy"))[0]

t0 = np.linspace(23 * 60 + 8, 23 * 60 + 8 + 100, 6)

# Plotting
log.info("Plotting results")

vlim = np.nanmin(np.maximum(watl, -botl)), np.nanmax(np.maximum(watl, -botl))

fig_x, ax = plt.subplots(
    3, 2, figsize=(15 / 2.54, 2 / 3 * 10 / 2.54), constrained_layout=True
)
i0 = np.argmin(np.abs(t * 1e-3 - t0[0]))
for ax_x, t0_x in zip(ax.reshape(-1), t0):
    ax_x.plot(x, -botl, color="k")
    i = np.argmin(np.abs(t * 1e-3 - t0_x))
    ax_x.plot(
        x,
        np.maximum(watl[i, :], -botl),
        color="#0066ff",
    )
    ax_x.axvline(-1450 + 1450 * ((t[i] - t[i0]) * 1e-3+5) / 100, color="k", alpha=0.2, lw=10)
    ax_x.grid(color="k", alpha=0.2)
    ax_x.set(ylabel="z (m)", ylim=vlim)
    ax_x.text(
        0.95,
        0.95,
        f"$T+{(t[i]-t[i0])*1e-3:.1f}s$",
        horizontalalignment="right",
        verticalalignment="top",
        transform=ax_x.transAxes,
    )
    ax_x.autoscale(axis="x", tight=True)

out = pathlib.Path(config.get("post", "out")).joinpath(f"trans")
log.info(f"Saving plots in '{out}'")
out.mkdir(parents=True, exist_ok=True)

fig_x.savefig(out.joinpath("x.pdf"))
fig_x.savefig(out.joinpath("x.jpg"), dpi=200)

log.info("Finished post-processing")
