package com.telephoners.krakyournet.ctf.repositories;

import com.telephoners.krakyournet.ctf.beans.Flag;
import com.telephoners.krakyournet.ctf.beans.Solution;
import com.telephoners.krakyournet.ctf.beans.Team;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.beans.tasks.Task;
import com.telephoners.krakyournet.ctf.core.ApplicationConfiguration;
import com.telephoners.krakyournet.ctf.helpers.DBObjectUtils;
import javafx.util.Pair;
import org.apache.commons.codec.binary.Hex;
import org.mongodb.morphia.Datastore;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Singleton
public class TasksRepository implements Repository
{

    private ApplicationConfiguration applicationConfiguration;
    private Datastore datastore;
    private TeamsRepository teamsRepository;
    private SolutionsRepository solutionsRepository;
    private String salt = "SECURE_SALT"; //todo: move to configuration!

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

    public Task getByLevel(int level)
    {
        return datastore.createQuery(Task.class)
                .filter("level", level)
                .get();
    }

    private Optional<Task> getByUserFlag(String username, String flagValue)
    {
        return getUserFlagsHashes(username).entrySet()
                .stream()
                .filter(flagsMapEntry -> flagsMapEntry.getKey().contains(flagValue))
                .map(Map.Entry::getValue)
                .map(this::getByLevel)
                .findFirst();
    }

    public List<Task> getAllPublic()
    {
        return datastore.createQuery(Task.class)
                .retrievedFields(true, DBObjectUtils.getPublicFields(Task.class))
                .asList();
    }

    public List<Task> getAll()
    {
        return datastore.createQuery(Task.class).asList();
    }

    public void add(Task task)
    {
        datastore.save(task);
    }

    //todo: refactor?
    public Map<List<String>, Integer> getUserFlagsHashes(String username)
    {
        return this.getAll().stream()
                .collect(Collectors.toMap(
                        task -> {
                            List<String> collect = task.getFlags().stream()
                                    .map(flag -> calculateHashValue(username, flag.getValue()))
                                    .collect(Collectors.toList());
                            return collect;
                        },
                        Task::getLevel
                ));
    }

    //todo: refactor with the function below
    private Optional<Pair<Task, Flag>> getTaskFlagPairByHashValue(User user, String userHash)
    {
        String username = user.getName();
        //todo: collapse lambdas
        Optional<Pair<Task, Flag>> matched = this.getAll().stream()
                .collect(Collectors.toMap(
                        task -> task,
                        Task::getFlags
                ))
                .entrySet()
                .stream()
                .map((Function<Map.Entry<Task, List<Flag>>, Pair<Task, Optional<Flag>>>) taskFlagsEntry -> {
                    Task task = taskFlagsEntry.getKey();
                    Optional<Flag> matchedFlag = taskFlagsEntry.getValue().stream()
                            .filter(new Predicate<Flag>()
                            {
                                @Override
                                public boolean test(Flag flag1)
                                {
                                    return calculateHashValue(username, flag1.getValue()).equals(userHash);
                                }
                            })
                            .findFirst();
                    return new Pair<Task, Optional<Flag>>(task, matchedFlag);
                })
                .filter(new Predicate<Pair<Task, Optional<Flag>>>()
                {
                    @Override
                    public boolean test(Pair<Task, Optional<Flag>> taskOptionalPair)
                    {
                        return taskOptionalPair.getValue().isPresent();
                    }
                })
                .map(new Function<Pair<Task, Optional<Flag>>, Pair<Task, Flag>>()
                {
                    @Override
                    public Pair<Task, Flag> apply(Pair<Task, Optional<Flag>> taskOptionalPair)
                    {
                        return new Pair<Task, Flag>(taskOptionalPair.getKey(), taskOptionalPair.getValue().get());
                    }
                })
                .findFirst();
        return matched;
        //todo: refactor
    }

    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 boolean isAlreadySubmittedSolution(Solution solution)
    {
        return solutionsRepository.exists(solution);
    }

    public boolean checkHash(User user, String hashValue)
    {
        //todo: refactor
        Optional<Pair<Task, Flag>> taskFlagPairOptional = getTaskFlagPairByHashValue(user, hashValue);
        if (!taskFlagPairOptional.isPresent()) {
            return false;
        }

        Pair<Task, Flag> taskFlagPair = taskFlagPairOptional.get();
        Task task = taskFlagPair.getKey();
        Optional<Team> team = teamsRepository.getTeamByUser(user);
        if (team.isPresent()) {
            //todo: combine ifs
            Solution solution = new Solution(team.get(), task, hashValue); //todo: conflict, solution stores task flag, should store hashValue!!
            if (!isAlreadySubmittedSolution(solution)) {
                solutionsRepository.add(solution);
                return true;
            }
        }
        return false;
    }

    public void clean()
    {
        datastore.getCollection(Task.class).drop();
    }

    //todo: should it be here?
    public List<Integer> getCompletedTasks(Team team)
    {
        Map<Integer, List<String>> teamSolutions = solutionsRepository.getTeamSolutions(team);
        return getAll().stream()
                .filter(task -> {
                    int numberOfFlags = task.getFlags().size();
                    List<String> teamTaskSolutions = teamSolutions.get(task.getLevel());
                    return teamTaskSolutions != null && teamTaskSolutions.size() == numberOfFlags;
                })
                .map(Task::getLevel)
                .collect(Collectors.toList());
    }
}