package com.telephoners.krakyournet.ctf.core;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.telephoners.krakyournet.ctf.beans.Flag;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.beans.tasks.Task;
import com.telephoners.krakyournet.ctf.repositories.SolutionsRepository;
import com.telephoners.krakyournet.ctf.repositories.TasksRepository;
import javafx.util.Pair;
import org.apache.commons.codec.binary.Hex;

import javax.inject.Named;
import java.security.MessageDigest;

@Singleton
public class HashValidator
{
    private ApplicationConfiguration applicationConfiguration;
    private MessageDigest messageDigest; //todo: use messageDigestProvider
    private SolutionsRepository solutionsRepository;
    private TasksRepository tasksRepository;

    @Inject
    public HashValidator(ApplicationConfiguration applicationConfiguration,
                         SolutionsRepository solutionsRepository,
                         TasksRepository tasksRepository,
                         final @Named("messageDigest") MessageDigest messageDigest)
    {
        this.applicationConfiguration = applicationConfiguration;
        this.solutionsRepository = solutionsRepository;
        this.tasksRepository = tasksRepository;
        this.messageDigest = messageDigest;
    }

    public String calculateHashValue(User user, String flagValue)
    {
        String combinedStrings = applicationConfiguration.getSalt() + user.getName() + flagValue;
        return Hex.encodeHexString(messageDigest.digest(combinedStrings.getBytes()));
    }

    public boolean checkHash(User user, String hashValue, int taskLevel)
    {
        Pair<Task, Flag> taskFlagPair = tasksRepository.getTaskFlagPairByHashValue(user, hashValue, taskLevel);

        //todo: move to solutionsRepository
        return solutionsRepository.submitSolution(user, taskFlagPair.getKey(), taskFlagPair.getValue(), hashValue);
    }
}
