package com.atlassian.stash.internal.web.fragments;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.ContextProvider;
import com.atlassian.bitbucket.commit.Commit;
import com.atlassian.stash.internal.watcher.InternalWatcherService;
import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.watcher.Watchable;
import com.google.common.collect.ImmutableMap;

import java.util.Map;
import java.util.Objects;

/**
 * @since 2.4
 */
public class IsWatchingContextProvider implements ContextProvider {

    private final AuthenticationContext authenticationContext;
    private final InternalWatcherService watcherService;

    public IsWatchingContextProvider(AuthenticationContext authenticationContext,
                                     InternalWatcherService watcherService) {
        this.authenticationContext = authenticationContext;
        this.watcherService = watcherService;
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
    }

    @Override
    public Map<String, Object> getContextMap(Map<String, Object> context) {
        boolean isWatching = false;

        ApplicationUser currentUser = authenticationContext.getCurrentUser();

        if (currentUser != null) {
            Watchable watchable = (Watchable) context.get("watchable");

            if (watchable != null) {
                isWatching = watcherService.isCurrentUserWatching(watchable);
            } else {
                Commit commit = (Commit) context.get("commit");

                isWatching = commit != null &&
                        Objects.equals(currentUser.getEmailAddress(), commit.getAuthor().getEmailAddress());
            }
        }

        return ImmutableMap.<String, Object>of("isWatching", isWatching);
    }
}
