from .interfaz import *
from numpy import linspace, sqrt

RESOLUTION = 100

class PruebaHorizontalFrame(SimpleInteractiveGraphFrame):
    def __init__(self, controlador):
        self.controlador = controlador
        super().__init__(controlador)

        # 1. Inicialización de interfaz general
        self.setPanels(toolBar=False)

        # 2. Panel de interacción con la gráfica
        self.panelPosVertical = tk.Frame(self.panelDown)
        self.panelPosVertical.pack(fill='x', expand=True)
        tk.Label(self.panelPosVertical, text='Posición\nvertical', font=TEXT_FONT, width=8).pack(side='left', padx=GRAL_PAD)
        self.sliderPosVertical = tk.Scale(self.panelPosVertical, from_=0, to=9, font=SLIDER_FONT, resolution=0.01, orient='horizontal', command=self.__updateGraph)
        self.sliderPosVertical.pack(side='left', fill='x', expand=True, padx=GRAL_PAD)
        self.sliderPosVertical.set(0)

        # 3. Gráfica
        self.xLim = [-3, 3]
        self.__updateGraph(init=True)

    def f(self, x):
        return x**2

    def __updateGraph(self, _=None, *, init=False):
        x = linspace(*self.xLim, RESOLUTION)
        y = self.f(x)
        posVertical = self.sliderPosVertical.get()

        if init:
            self.fig.suptitle(r'$f(x)=x^{2}$')
            self.ejes.set_xlabel('X')
            self.ejes.set_ylabel('Y')
            self.setLineasEjes(self.ejes)
            self.ejes.grid(True)
            self.ejes.plot(x, y, color='black')
            self.ejes.annotate('', xy=(x[-1], y[-1]), xytext=(x[-2], y[-2]), arrowprops=dict(arrowstyle='->', color='black', lw=1))
            self.ejes.annotate('', xy=(-x[-1], y[-1]), xytext=(-x[-2], y[-2]), arrowprops=dict(arrowstyle='->', color='black', lw=1))
            self.horLine, = self.ejes.plot(self.xLim, [posVertical, posVertical], color='red', linestyle='dashdot')
            self.pointsLine, = self.ejes.plot([-sqrt(posVertical), sqrt(posVertical)], [posVertical, posVertical], linewidth=0, marker='o', color='red')
            plt.tight_layout()
        else:
            self.horLine.set_data(self.xLim, [posVertical, posVertical])
            self.pointsLine.set_data([-sqrt(posVertical), sqrt(posVertical)], [posVertical, posVertical])

        self.canvas.draw()

def main():
    app = Controlador(
        title='III. Funciones — Prueba de la Recta horizontal',
        firstFrame=PruebaHorizontalFrame,
        height=800, width=775
    )
    app.mainloop()

if __name__ == '__main__':
    main()
