import argparse
import configparser
import logging
import pathlib

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
from scipy import fft

from .olaflow import OFModel

parser = argparse.ArgumentParser(description="Convert swash output to olaFlow input")
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("-c", "--config", default="config.ini")
parser.add_argument("-o", "--output", type=pathlib.Path)
args = parser.parse_args()

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

log.info("Starting sws -> olaFlow converter")
config = configparser.ConfigParser()
config.read(args.config)
level = config.getfloat("bathy", "level", fallback=0.0)

sws_out = pathlib.Path(config.get("swash", "np_out"))


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


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

vel = data("vel")
watl = data("watl")

x0 = config.getfloat("olaflow", "x0")
arg_x0 = np.argmin(np.abs(x - x0))
t0 = config.getfloat("olaflow", "t0")
tf = config.getfloat("olaflow", "tf")
arg_t0 = -np.argmax(t_[::-1] < (t0 * 1e3))
arg_tf = np.argmax(t_ > (tf * 1e3)) + 1

t = t_[arg_t0:arg_tf] * 1e-3
t = t - t.min()
wl = watl[arg_t0:arg_tf, arg_x0]
v = vel[0, arg_t0:arg_tf, arg_x0]

olaflow_root = args.output
org = olaflow_root.joinpath("constant", "waveDict_paddle.org").read_text()
org = org.replace("{n}", str(t.size))
org = org.replace("{t}", "\n".join(t.astype(np.str_)))
org = org.replace("{v}", "\n".join(v.astype(np.str_)))
org = org.replace("{eta}", "\n".join(wl.astype(np.str_)))
olaflow_root.joinpath("constant", "waveDict").write_text(org)

fig, (ax, ax2) = plt.subplots(2)
ax.plot(t, wl)
ax.autoscale(True, "x", tight=True)
ax.set(xlabel="t (s)", ylabel="z (m)")
ax2.plot(t, v)
ax2.autoscale(True, "x", tight=True)
ax2.set(xlabel="t (s)", ylabel="U (m/s)")
fig.savefig(olaflow_root.joinpath("constant", "wave.pdf"))
