package com.alttd.altitudeweb.mappers;

import com.alttd.altitudeweb.database.votingplugin.VotingStatsRow;
import com.alttd.altitudeweb.model.VoteDataDto;
import com.alttd.altitudeweb.model.VoteInfoDto;
import com.alttd.altitudeweb.model.VoteStatsDto;
import com.alttd.altitudeweb.model.VoteStreakDto;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class VotingStatsRowToVoteDataDto {

    public VoteDataDto map(VotingStatsRow votingStatsRow) {
        VoteDataDto voteDataDto = new VoteDataDto();
        voteDataDto.setVoteStats(getVoteStats(votingStatsRow));
        voteDataDto.setVoteStreak(getVoteStreak(votingStatsRow));
        voteDataDto.setBestVoteStreak(getBestVoteStreak(votingStatsRow));
        voteDataDto.setAllVoteInfo(getVoteInfo(votingStatsRow.lastVotes()));
        return voteDataDto;
    }

    private VoteStreakDto getVoteStreak(VotingStatsRow votingStatsRow) {
        VoteStreakDto voteStreakDto = new VoteStreakDto();
        voteStreakDto.setDailyStreak(votingStatsRow.dailyStreak());
        voteStreakDto.setWeeklyStreak(votingStatsRow.weeklyStreak());
        voteStreakDto.setMonthlyStreak(votingStatsRow.monthlyStreak());
        return voteStreakDto;
    }

    private VoteStreakDto getBestVoteStreak(VotingStatsRow votingStatsRow) {
        VoteStreakDto voteStreakDto = new VoteStreakDto();
        voteStreakDto.setDailyStreak(votingStatsRow.bestDailyStreak());
        voteStreakDto.setWeeklyStreak(votingStatsRow.bestWeeklyStreak());
        voteStreakDto.setMonthlyStreak(votingStatsRow.bestMonthlyStreak());
        return voteStreakDto;
    }


    private VoteStatsDto getVoteStats(VotingStatsRow votingStatsRow) {
        VoteStatsDto voteStatsDto = new VoteStatsDto();
        voteStatsDto.setDaily(votingStatsRow.totalVotesToday());
        voteStatsDto.setWeekly(votingStatsRow.totalVotesThisWeek());
        voteStatsDto.setMonthly(votingStatsRow.totalVotesThisMonth());
        voteStatsDto.setTotal(votingStatsRow.totalVotesAllTime());
        return voteStatsDto;
    }

    private List<VoteInfoDto> getVoteInfo(String lastVotes) {
        return Arrays.stream(lastVotes.split("%line%"))
                .map(voteInfo -> {
                    String[] siteAndTimestamp = voteInfo.split("//");
                    VoteInfoDto voteInfoDto = new VoteInfoDto();
                    voteInfoDto.setSiteName(siteAndTimestamp[0]);
                    voteInfoDto.setLastVoteTimestamp(Long.parseLong(siteAndTimestamp[1]));
                    return voteInfoDto;
                })
                .toList();
    }
}
