package com.izouma.nineth.domain;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.izouma.nineth.dto.MenuDTO;
import com.izouma.nineth.security.Authority;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Where(clause = "active = 1")
public class Menu extends BaseEntity implements Serializable {
    private String name;

    private String path;

    private String icon;

    private Integer sort;

    private Long parent;

    private Boolean root;

    private Boolean enabled;

    private Boolean active;

    private String category;

    @OneToMany
    @JoinColumn(name = "parent", insertable = false, updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    List<Menu> children;

    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH})
    @JoinTable(
            name = "menu_authority",
            joinColumns = {@JoinColumn(name = "menu_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "authority", referencedColumnName = "name")})
    @ExcelIgnore
    private Set<Authority> authorities = new HashSet<>();

    public static Menu from(MenuDTO menuDTO) {
        Menu menu = Menu.builder()
                .name(menuDTO.getName())
                .path(menuDTO.getPath())
                .icon(menuDTO.getIcon())
                .sort(menuDTO.getSort())
                .parent(menuDTO.getParent())
                .root(menuDTO.getRoot())
                .enabled(menuDTO.getEnabled())
                .active(menuDTO.getActive())
                .category(menuDTO.getCategory())
                .children(null)
                .build();
        menu.setId(menuDTO.getId());
        return menu;
    }
}
