package cz.muni.fi.pa165.soccermanager.mapper;

import cz.muni.fi.pa165.soccermanager.dto.MatchDto;
import cz.muni.fi.pa165.soccermanager.dto.MatchScoreDto;
import cz.muni.fi.pa165.soccermanager.dto.request.CreateMatchRequest;
import cz.muni.fi.pa165.soccermanager.dto.request.UpdateMatchDto;
import cz.muni.fi.pa165.soccermanager.entity.Team;
import cz.muni.fi.pa165.soccermanager.factory.MatchFactory;
import cz.muni.fi.pa165.soccermanager.entity.Match;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

import java.util.List;

/**
 * @author Stanislav Koshchienko (uco: 506549)
 */
@Mapper(uses = MatchFactory.class)
public interface MatchMapper {

    MatchDto map(Match source);

    @Mapping(target = "defender", ignore = true)
    @Mapping(target = "challenger", ignore = true)
    @Mapping(target = "id", ignore = true)
    Match map(CreateMatchRequest source);

    List<MatchDto> map(List<Match> source);

    @Mapping(target = "defenderGoals", source = "result.defenderGoals")
    @Mapping(target = "challengerGoals", source = "result.challengerGoals")
    @Mapping(target = "id", ignore = true)
    void mapOnUpdate(@MappingTarget Match target, UpdateMatchDto source);

    @AfterMapping
    default void map(@MappingTarget MatchDto dto, Match source) {
        dto.setResult(new MatchScoreDto());
        dto.getResult().setChallengerGoals(source.getChallengerGoals());
        dto.getResult().setDefenderGoals(source.getDefenderGoals());
    }

    @AfterMapping
    default void setPlayPlace(MatchDto dto, @MappingTarget Match match) {
        if (!match.getPlayPlace().isBlank() && match.getDefender() != null) {
            match.setPlayPlace(match.getDefender().getGround());
        }
    }

    default Long map(Team team) {
        return team == null ? null : team.getId();
    }
}
