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;
import java.util.stream.Collectors;

/**
 * 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;
    }

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

    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.getAll().stream()
                .collect(Collectors.toMap(
                        task -> task,
                        task -> calculateHashValue(username, task.getFlag().getValue())
                ))
                .entrySet()
                .stream()
                .filter(taskHashEntry -> taskHashEntry.getValue().equals(hash))
                .findFirst();

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

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


}
