package ru.vyatsu.qr_access_admin.door.view;

import ru.vyatsu.qr_access_admin.common.MainLayout;
import ru.vyatsu.qr_access_admin.door.component.DoorEditor;
import ru.vyatsu.qr_access_admin.door.entity.DoorEntity;
import ru.vyatsu.qr_access_admin.door.entity.DoorRepository;
import ru.vyatsu.qr_access_admin.unit.entity.UnitRepository;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;

import java.util.List;

@Route(value = "doors", layout = MainLayout.class)
@PageTitle("Двери")
public class DoorView extends VerticalLayout {
    private final Grid<DoorEntity> grid;
    private final DoorRepository repository;
    private final DoorEditor editor;

    public DoorView(DoorRepository repository, UnitRepository unitRepository) {
        this.repository = repository;

        var addButton = new Button("Добавить дверь", VaadinIcon.PLUS.create());

        grid = new Grid<>(DoorEntity.class);
        editor = new DoorEditor(unitRepository);

        var actionsLayout = new HorizontalLayout(addButton);
        add(actionsLayout, grid, editor);

        this.configureEditor();

        addButton.addClickListener(e -> editDoor(new DoorEntity()));

        grid.setHeight("200px");

        grid.asSingleSelect().addValueChangeListener(e -> editDoor(e.getValue()));

        refreshDoorsGrid();
    }

    private void refreshDoorsGrid() {
        List<DoorEntity> entities = repository.findAll();

        grid.setItems(entities);
    }

    private void editDoor(DoorEntity door) {
        if (door == null) {
            editor.setVisible(false);
        } else {
            editor.setVisible(true);
            editor.setCurrentDoor(door);
        }
    }

    private void configureEditor() {
        editor.setVisible(false);

        editor.setSaveListener(door -> {
            repository.save(door);
            refreshDoorsGrid();
            editDoor(null);
        });

        editor.setDeleteListener(door -> {
            repository.deleteById(door.getId());
            refreshDoorsGrid();
            editDoor(null);
        });

        editor.setCancelListener(() -> editDoor(null));
    }
}
