package com.alttd.altitudeweb.services.site;

import com.alttd.altitudeweb.database.Databases;
import com.alttd.altitudeweb.database.votingplugin.VotingPluginUsersMapper;
import com.alttd.altitudeweb.database.votingplugin.VotingStatsRow;
import com.alttd.altitudeweb.mappers.VotingStatsRowToVoteDataDto;
import com.alttd.altitudeweb.model.VoteDataDto;
import com.alttd.altitudeweb.setup.Connection;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
@RequiredArgsConstructor
public class VoteService {

    private final VotingStatsRowToVoteDataDto votingStatsRowToVoteDataDto;

    public Optional<VoteDataDto> getVoteStats(UUID uuid) {
        CompletableFuture<Optional<VoteDataDto>> voteDataDtoFuture = new CompletableFuture<>();
        Connection.getConnection(Databases.VOTING_PLUGIN).runQuery(sqlSession -> {
            try {
                VotingPluginUsersMapper votingPluginUsersMapper = sqlSession.getMapper(VotingPluginUsersMapper.class);
                Optional<VotingStatsRow> optionalVotingStatsRow = votingPluginUsersMapper.getStatsByUuid(uuid);
                if (optionalVotingStatsRow.isEmpty()) {
                    log.debug("No voting stats found for {}", uuid);
                    voteDataDtoFuture.complete(Optional.empty());
                    return;
                }

                VotingStatsRow votingStatsRow = optionalVotingStatsRow.get();

                VoteDataDto voteDataDto = votingStatsRowToVoteDataDto.map(votingStatsRow);
                voteDataDtoFuture.complete(Optional.of(voteDataDto));
            } catch (Exception e) {
                log.error("Failed to get vote data for {}", uuid, e);
                voteDataDtoFuture.completeExceptionally(e);
            }
        });
        return voteDataDtoFuture.join();//TODO handle exception
    }
}
