package org.mercury_im.messenger.core.util;

import java.util.ArrayList;
import java.util.List;

public class DiffUtil<T> {

    public static <T> Diff<T> diff(List<T> before, List<T> after) {
        List<T> removed = getRemovedItems(before, after);
        List<T> added = getAddedItems(before, after);
        List<T> retained = getRetainedItems(before, after);
        return new Diff<>(added, retained, removed);
    }

    private static <T> List<T> getRemovedItems(List<T> before, List<T> after) {
        List<T> withoutRetained = new ArrayList<>(before);
        withoutRetained.removeAll(after);
        return withoutRetained;
    }

    private static <T> List<T> getAddedItems(List<T> before, List<T> after) {
        List<T> withoutPrevious = new ArrayList<>(after);
        withoutPrevious.removeAll(before);
        return withoutPrevious;
    }

    private static <T> List<T> getRetainedItems(List<T> before, List<T> after) {
        List<T> retained = new ArrayList<>(before);
        retained.retainAll(after);
        return retained;
    }

    public static class Diff<T> {

        private final List<T> added;
        private final List<T> retained;
        private final List<T> removed;

        public Diff(List<T> added, List<T> retained, List<T> removed) {
            this.added = added;
            this.retained = retained;
            this.removed = removed;
        }

        public List<T> getAdded() {
            return added;
        }

        public List<T> getRetained() {
            return retained;
        }

        public List<T> getRemoved() {
            return removed;
        }
    }
}
