import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler

from plot_helpers import CO, bold_ticks


def fig6_7():
    a = 0
    b = 1

    # f(x)
    nxe = 100
    xe = np.linspace(a, b, nxe)
    ye = np.zeros(nxe)
    for ix in range(nxe):
        ye[ix] = f(xe[ix])

    # interpolation points
    xd = np.array([0, 0.25, 0.5, 0.75, 1], dtype=float)
    yd = np.array([f(0), f(0.25), f(0.5), f(0.75), f(1)])
    x1 = a
    x2 = 0.25 * (a + b)
    x3 = 0.5 * (a + b)
    y1 = f(x1)
    y2 = f(x2)
    y3 = f(x3)

    # p_2(x)
    nx = 50
    x = np.linspace(x1, x3, nx)
    s = np.zeros(nx)
    for ix in range(nx):
        s[ix] = p2(x[ix], x1, x2, x3, y1, y2, y3)

    x1 = 0.5 * (a + b)
    x2 = 0.75 * (a + b)
    x3 = a + b
    y1 = f(x1)
    y2 = f(x2)
    y3 = f(x3)
    nx = 50
    xx = np.linspace(x1, x3, nx)
    ss = np.zeros(nx)
    for ix in range(nx):
        ss[ix] = p2(xx[ix], x1, x2, x3, y1, y2, y3)

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(8.8, 3.3))
    fig.subplots_adjust(left=0.09, right=0.98, bottom=0.22, top=0.98)
    ax.set_prop_cycle(cycler(color=CO))

    ax.plot(x, s, "r", linewidth=1.5)
    ax.plot(xe, ye, "--b", linewidth=1.5)
    ax.plot(xd, yd, "ob", markersize=9, linewidth=2)
    ax.plot(xx, ss, "r", linewidth=1.8)
    ax.grid(True)
    ax.set_xlabel("x-axis")
    ax.set_ylabel("y-axis")

    ax.legend(
        [r" $p_2(x)$", r" $f(x)$"],
        loc="lower left",
        prop={"size": 14, "weight": "bold"},
    )

    ax.set_xlim(0, 1)
    ax.set_ylim(-1, 1.1)
    ax.set_xticks([0, 0.25, 0.5, 0.75, 1])
    # ax.yaxis.grid(False, which="minor")
    bold_ticks(ax, 14)
    plt.show()

    # plt.savefig('/Users/mark/Desktop/simp0.eps')


def p2(x, x1, x2, x3, y1, y2, y3):
    l1 = (x - x2) * (x - x3) / ((x1 - x2) * (x1 - x3))
    l2 = (x - x1) * (x - x3) / ((x2 - x1) * (x2 - x3))
    l3 = (x - x1) * (x - x2) / ((x3 - x1) * (x3 - x2))
    y = y1 * l1 + y2 * l2 + y3 * l3
    return y


def f(x):
    # y = np.cos(2*np.pi*x)
    # y = np.exp(x)
    y = np.cos(4 * x ** 2)
    return y


if __name__ == "__main__":
    fig6_7()
