package com.izouma.immall.web;

import com.izouma.immall.domain.Menu;
import com.izouma.immall.repo.MenuRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {
    @Autowired
    private MenuRepo menuRepo;

    @GetMapping("/userMenu")
    public List<Menu> userMenu(String name) {
        List<Menu> menuList = menuRepo.findByNameAndRootTrue(name);
        menuList.forEach(this::sortMenu);
        return menuList;
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public List<Menu> all() {
        List<Menu> menuList = menuRepo.findByRootTrue();
        menuList.forEach(this::sortMenu);
        return menuList;
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Menu save(Menu menu) {
        if (menu.getSort() == null) {
            menu.setSort(menuRepo.nextSort());
        }
        menuRepo.save(menu);
        return menu;
    }

    private void sortMenu(Menu menu) {
        if (menu.getChildren() != null) {
            menu.getChildren().sort(Comparator.comparingInt(Menu::getSort));
            menu.getChildren().forEach(this::sortMenu);
        }
    }
}
