package ru.yandex.webmaster3.storage.checklist.data;

import java.util.EnumMap;
import java.util.Map;

import ru.yandex.webmaster3.core.checklist.data.SiteProblemSeverityEnum;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemState;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemStorageType;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;

/**
 * @author avhaliullin
 */
public class SummarySiteProblemsInfo {
    private final int problemsWeight;
    private final int undefinedProblemsWeight;
    private final Map<SiteProblemTypeEnum, SiteProblemState> problem2State;

    public SummarySiteProblemsInfo(int problemsWeight, int undefinedProblemsWeight, Map<SiteProblemTypeEnum, SiteProblemState> problem2State) {
        this.problemsWeight = problemsWeight;
        this.undefinedProblemsWeight = undefinedProblemsWeight;
        this.problem2State = problem2State;
    }

    public int getProblemsWeight() {
        return problemsWeight;
    }

    public int getUndefinedProblemsWeight() {
        return undefinedProblemsWeight;
    }

    public boolean isHaveFatalProblems() {
        return problem2State.entrySet().stream()
                .anyMatch(entry -> entry.getKey().getSeverity() == SiteProblemSeverityEnum.FATAL && entry.getValue().isPresent());
    }

    public Map<SiteProblemTypeEnum, SiteProblemState> getProblem2State() {
        return problem2State;
    }

    public boolean isPresent(SiteProblemTypeEnum problemType){
        return problem2State.containsKey(problemType) && problem2State.get(problemType).isPresent();
    }

    public SummarySiteProblemsInfo merge(SummarySiteProblemsInfo that) {
        if (that == null) {
            return this;
        }

        Map<SiteProblemTypeEnum, SiteProblemState> problem2State = new EnumMap<>(SiteProblemTypeEnum.class);
        // TODO важен порядок, после избавления от поколений все это уже будет не важно
        problem2State.putAll(that.problem2State);
        problem2State.putAll(this.problem2State);
        return new SummarySiteProblemsInfo(
                problemsWeight + that.getProblemsWeight(),
                undefinedProblemsWeight + that.getUndefinedProblemsWeight(),
                problem2State);
    }

    public SummarySiteProblemsInfo filter(SiteProblemStorageType storage) {
        problem2State.entrySet().removeIf(entry -> entry.getKey().getStorageType() != storage);
        return this;
    }
}
