package ru.yandex.qe.dispenser.domain.dao.goal;

import java.util.Collection;

import org.jetbrains.annotations.NotNull;
import org.springframework.dao.EmptyResultDataAccessException;

import ru.yandex.qe.dispenser.domain.dao.InMemoryLongKeyDaoImpl;
import ru.yandex.qe.dispenser.domain.exception.SingleMessageException;

public class GoalDaoImpl extends InMemoryLongKeyDaoImpl<Goal> implements GoalDao {
    @Override
    public boolean upsert(final Collection<BaseGoal> goals) {
        goals.forEach(this::upsert);
        return true;
    }

    @NotNull
    @Override
    public Goal read(final @NotNull Long id) {
        try {
            return super.read(id);
        } catch (EmptyResultDataAccessException e) {
            throw SingleMessageException.illegalArgument("goal.not.found.try.again.later", id);
        }
    }

    private void upsert(final BaseGoal goal) {
        final Goal storedGoal = id2obj.get(goal.getId());
        final Goal resultGoal;
        if (storedGoal == null) {
            resultGoal = new Goal(goal.getId(), goal.getName(), goal.getImportance(), goal.getStatus(), OkrAncestors.EMPTY);
        } else {
            resultGoal = new Goal(goal.getId(), goal.getName(), goal.getImportance(), goal.getStatus(), storedGoal.getOkrParents());
        }
        id2obj.put(goal.getId(), resultGoal);
    }

    @Override
    public void updateOrkAncestors(final Long goalId, final OkrAncestors okrAncestors) {
        final Goal goal = read(goalId);
        id2obj.put(goalId, new Goal(goal.getId(), goal.getName(), goal.getImportance(), goal.getStatus(), okrAncestors));
    }

}
