from .interfaz import *
from hilbertcurve.hilbertcurve import HilbertCurve

MAX_N = 9

class CurvasHilbertFrame(SimpleInteractiveGraphFrame):
    def __init__(self, controlador):
        self.controlador = controlador
        super().__init__(controlador)
        
        # 1. Inicialización de interfaz general
        self.setPanels(showEjes=False)

        # 3. Panel de interacción con la gráfica
        self.panelN = tk.Frame(self.panelDown)
        self.panelN.pack(fill='x', expand=True)
        tk.Label(self.panelN, text='n', font=TEXT_FONT, width=2).pack(side='left', padx=GRAL_PAD)
        self.sliderN = tk.Scale(self.panelN, from_=1, to=MAX_N, resolution=1, font=SLIDER_FONT, orient='horizontal', command=self.__updateGraph)
        self.sliderN.pack(side='left', fill='x', expand=True, padx=GRAL_PAD)
        self.sliderN.set(1)

        # 2. Gráfica
        self.__updateGraph(init=True)

    def __computeHilbertPoints(self):
        self.points = {}
        for n in range(1, MAX_N + 1):
            hilbert = HilbertCurve(n, 2)
            points = [hilbert.point_from_distance(i) for i in range(2**(n*2))]
            self.points[n] = points

    def __updateGraph(self, _=None, *, init=False):
        if init:
            self.__computeHilbertPoints()
            x, y = zip(*self.points[1])
            self.hilbertCurve, = self.ejes.plot(x, y, color='black')
            plt.tight_layout()
        else:
            n = self.sliderN.get()
            x, y = zip(*self.points[n])
            self.hilbertCurve.set_data(x, y)
            self.ejes.relim()
            self.ejes.autoscale_view()
            self.canvas.draw()

def main():
    app = Controlador(
        title='IV. Sucesiones — Curva de Hilbert',
        firstFrame=CurvasHilbertFrame,
        height=775, width=775
    )
    app.mainloop()
        
if __name__ == '__main__':
    main()
