package cn.lihongjie.coal.resource.mapper;

import cn.lihongjie.coal.base.mapper.BaseMapper;
import cn.lihongjie.coal.resource.dto.CreateResourceDto;
import cn.lihongjie.coal.resource.dto.ResourceDto;
import cn.lihongjie.coal.resource.dto.ResourceTreeDto;
import cn.lihongjie.coal.resource.dto.UpdateResourceDto;
import cn.lihongjie.coal.resource.entity.ResourceEntity;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.mapstruct.*;
import org.mapstruct.control.DeepClone;

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

@Mapper(
        componentModel = MappingConstants.ComponentModel.SPRING,
        uses = {cn.lihongjie.coal.base.mapper.CommonMapper.class, cn.lihongjie.coal.base.mapper.CommonEntityMapper.class},
        mappingControl = DeepClone.class)
public interface ResourceMapper
        extends BaseMapper<ResourceEntity, ResourceDto, CreateResourceDto, UpdateResourceDto> {
    @Mappings({@org.mapstruct.Mapping(target = "parent", source = "parent.id")})
    ResourceDto toDto(ResourceEntity user);

    ResourceEntity toEntity(CreateResourceDto request);

    void updateEntity(@MappingTarget ResourceEntity entity, UpdateResourceDto dto);

    List<ResourceTreeDto> toTreeDto(List<ResourceEntity> byTypeAndParentIsNull);

    @Mappings({@org.mapstruct.Mapping(target = "parent", source = "parent.id")})
    ResourceTreeDto toTreeDto(ResourceEntity byTypeAndParentIsNull);

    @AfterMapping
    default void afterMappingTreeDto(
            @MappingTarget ResourceTreeDto treeDto, ResourceEntity entity) {

        if (CollectionUtils.isNotEmpty(treeDto.getChildren())) {

            treeDto.getChildren()
                    .sort(
                            Comparator.comparing(
                                    x -> ObjectUtils.defaultIfNull(x.getSortKey(), 99999)));
        }
    }

    ResourceEntity toEntity(ResourceDto rd);
}
