package core;

import objects.Solution;
import objects.Task;
import org.apache.commons.codec.binary.Hex;
import repositories.SolutionsRepository;
import repositories.TasksRepository;
import repositories.TeamsRepository;

import javax.inject.Inject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Optional;

/**
 * Created by gpietrus on 20.02.2016.
 */
public class FlagChecker {

    private String salt = "SECURE_SALT"; //todo
    private TasksRepository tasksRepository;
    private TeamsRepository teamsRepository;
    private SolutionsRepository solutionsRepository;
    private ApplicationConfiguration applicationConfiguration;

    @Inject
    public FlagChecker(ApplicationConfiguration applicationConfiguration, TasksRepository tasksRepository, TeamsRepository teamsRepository, SolutionsRepository solutionsRepository) {
        this.applicationConfiguration = applicationConfiguration;
        this.tasksRepository = tasksRepository;
        this.teamsRepository = teamsRepository;
        this.solutionsRepository = solutionsRepository;
    }

    public String calculateHashValue(String username, String flagValue) { //todo
        String combinedStrings = salt + username + flagValue; //todo
        MessageDigest md5 = null;//todo: discuss
        try {
            md5 = MessageDigest.getInstance(applicationConfiguration.getFlagHashMethod());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String encodedHash = Hex.encodeHexString(md5.digest(combinedStrings.getBytes()));
        return encodedHash;
    }

    private void acceptSolution(String username, Task task) {
        //todo: getname, of get id?
        solutionsRepository.add(new Solution(teamsRepository.getTeamByUser(username).getName(), task.getName()));
    }

    private boolean compareHash(String hash, String username) throws Exception {
        Optional<Map.Entry<Task, String>> matchingHash = tasksRepository.getUserFlagsHashes(username)
                .stream()
                .filter(taskHashEntry -> taskHashEntry.getValue().equals(hash))
                .findFirst();

        if (matchingHash.isPresent()) {
            acceptSolution(username, matchingHash.get().getKey());
            return true;
        }
        return false;
    }

    public boolean checkFlag(String username, String flagValue) throws Exception {
        String hash = calculateHashValue(username, flagValue);
        return compareHash(hash, username);
    }


}
