package core;

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

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;

    @Inject
    public FlagChecker(TasksRepository tasksRepository, TeamsRepository teamsRepository, SolutionsRepository solutionsRepository) {
        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("MD5");
        } 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);
    }


}
