package com.atlassian.bitbucket.rest.pull;

import com.atlassian.bitbucket.pull.*;
import com.atlassian.bitbucket.rest.activity.RestActivity;
import com.atlassian.bitbucket.rest.annotation.JsonSurrogate;
import com.atlassian.bitbucket.rest.user.RestApplicationUser;
import com.atlassian.bitbucket.rest.util.RestDocUtils;
import com.atlassian.bitbucket.rest.util.RestPage;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.annotation.Nonnull;
import java.util.Date;
import java.util.function.Function;

@JsonSerialize
@JsonSurrogate(PullRequestActivity.class)
public class RestPullRequestActivity extends RestActivity {

    public static final Function<PullRequestActivity, RestPullRequestActivity> REST_TRANSFORM = activity -> {
        RestPullRequestActivityVisitor visitor = new RestPullRequestActivityVisitor();

        activity.accept(visitor);

        return visitor.getActivity();
    };

    public RestPullRequestActivity(PullRequestActivity activity) {
        this(activity.getId(), activity.getCreatedDate(), new RestApplicationUser(activity.getUser()), activity.getAction());
    }

    // Required for REST documentation
    protected RestPullRequestActivity(long id, Date createdDate, RestApplicationUser user, PullRequestAction action) {
        super(id, createdDate, user);

        put("action", action);
    }

    public static class RestPullRequestActivityVisitor implements PullRequestActivityVisitor {

        private RestPullRequestActivity activity;

        public RestPullRequestActivity getActivity() {
            return activity;
        }

        @Override
        public void visit(@Nonnull PullRequestActivity activity) {
            this.activity = new RestPullRequestActivity(activity);
        }

        @Override
        public void visit(@Nonnull PullRequestCommentActivity activity) {
            this.activity = new RestPullRequestCommentActivity(activity);
        }

        @Override
        public void visit(@Nonnull PullRequestMergeActivity activity) {
            this.activity = new RestPullRequestMergeActivity(activity);
        }

        @Override
        public void visit(@Nonnull PullRequestRescopeActivity activity) {
            this.activity = new RestPullRequestRescopeActivity(activity);
        }

        @Override
        public void visit(@Nonnull PullRequestReviewersUpdatedActivity activity) {
            this.activity = new RestPullRequestReviewersUpdatedActivity(activity);
        }
    }

    // REST Documentation Examples

    public static final RestPage<RestPullRequestActivity> PAGE_EXAMPLE = RestDocUtils.pageOf(
            RestPullRequestCommentActivity.RESPONSE_EXAMPLE,
            RestPullRequestRescopeActivity.RESPONSE_EXAMPLE,
            RestPullRequestMergeActivity.RESPONSE_EXAMPLE
    );

}
