package com.example.views;

import com.example.js.CommonJS;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.sidenav.SideNav;
import com.vaadin.flow.component.sidenav.SideNavItem;
import com.vaadin.flow.router.Layout;

@Layout
public class MainLayout extends AppLayout {

    private final Button themeToggle = new Button(VaadinIcon.MOON.create());

    public MainLayout() {
        DrawerToggle toggle = new DrawerToggle();

        Span title = new Span("Chart App");
        title.addClassName("dialect-title");

        Span spacer = new Span();
        spacer.getStyle().set("flex-grow", "1");

        themeToggle.addThemeVariants(ButtonVariant.TERTIARY, ButtonVariant.LUMO_ICON);
        themeToggle.setAriaLabel("Farbschema wechseln");
        themeToggle.addClickListener(e ->
                getElement().executeJs(CommonJS.TOGGLE_THEME_JS).then(String.class, this::applyIconFor));

        addToNavbar(toggle, title, spacer, themeToggle);

        getElement().executeJs(CommonJS.INIT_THEME_JS).then(String.class, this::applyIconFor);

        SideNav nav = new SideNav();
        nav.addItem(new SideNavItem("Dashboard", DashboardView.class,
                VaadinIcon.DASHBOARD.create()));
        nav.addItem(new SideNavItem("Formular", FormView.class,
                VaadinIcon.FORM.create()));
        nav.addItem(new SideNavItem("Tabelle", TableView.class,
                VaadinIcon.TABLE.create()));

        addToDrawer(nav);
    }

    private void applyIconFor(String theme) {
        themeToggle.setIcon("dark".equals(theme) ? VaadinIcon.SUN_O.create() : VaadinIcon.MOON.create());
    }
}
