package com.atlassian.bitbucket.internal.mirroring.mirror.rest.webhook.cloud;

import com.atlassian.bitbucket.internal.mirroring.mirror.rest.cloud.RestCloudExternalGitRefChange;
import com.atlassian.bitbucket.internal.mirroring.mirror.rest.cloud.RestCloudExternalRefChange;
import com.atlassian.bitbucket.internal.mirroring.mirror.webhook.RepositoryRefsChangedWebHookEvent;
import com.atlassian.bitbucket.internal.mirroring.mirror.webhook.WebHookEventVisitor;
import com.atlassian.bitbucket.repository.RefChange;
import com.atlassian.bitbucket.scm.git.GitScm;
import com.atlassian.bitbucket.util.MoreStreams;

import javax.annotation.Nonnull;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.atlassian.bitbucket.internal.mirroring.mirror.rest.webhook.cloud.RestCloudWebHookPropertyNames.CHANGES;
import static com.atlassian.bitbucket.internal.mirroring.mirror.rest.webhook.cloud.RestCloudWebHookPropertyNames.PUSH;

public class RestCloudRepositoryPushWebHookEvent extends BaseRestCloudRepositoryWebHookEvent implements RepositoryRefsChangedWebHookEvent {

    @SuppressWarnings("unused")
    public RestCloudRepositoryPushWebHookEvent() {
    }

    public RestCloudRepositoryPushWebHookEvent(Map<String, ?> values) {
        super(values);
    }

    @SuppressWarnings("unchecked")
    @NotNull
    @Override
    public List<RefChange> getChanges() {
        Map<?, ?> push = (Map<?, ?>) get(PUSH);
        Iterable<Object> changes = (Iterable<Object>) push.get(CHANGES);

        // special handling of git refs - the ids of the refs need full qualification
        if (GitScm.ID.equals(getRepository().getScmId())) {
            return MoreStreams.streamIterable(changes)
                    .map(RestCloudExternalGitRefChange::valueOf)
                    .collect(Collectors.toList());
        } else {
            return MoreStreams.streamIterable(changes)
                    .map(RestCloudExternalRefChange::valueOf)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public <T> T visit(@Nonnull WebHookEventVisitor<T> visitor) {
        return visitor.accept(this);
    }
}
