java/admin/src/main/java/com/exadel/frs/mapper/AppMapper.java
/*
 * Copyright (c) 2020 the original author or authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

package com.exadel.frs.mapper;

import com.exadel.frs.dto.ui.AppResponseDto;
import com.exadel.frs.commonservice.entity.App;
import com.exadel.frs.commonservice.entity.User;
import com.exadel.frs.commonservice.entity.UserAppRole;
import java.util.List;
import org.mapstruct.Context;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

@Mapper(uses = {UserAppRoleMapper.class, MlModelMapper.class, UserMapper.class})
public interface AppMapper {

    @Mapping(source = "guid", target = "id")
    @Mapping(source = "app", target = "role", qualifiedByName = "getRole")
    @Mapping(source = "app", target = "owner", qualifiedByName = "getOwner")
    AppResponseDto toResponseDto(App app, @Context Long userId);

    List<AppResponseDto> toResponseDto(List<App> apps, @Context Long userId);

    @Named("getOwner")
    default User getOwner(App app) {
        return app.getOwner()
                  .map(UserAppRole::getUser)
                  .orElse(null);
    }

    @Named("getRole")
    default String getRole(App app, @Context Long userId) {
        return app.getUserAppRole(userId)
                  .map(UserAppRole::getRole)
                  .map(Enum::name)
                  .orElse(null);
    }
}