package com.atlassian.stash.internal.notification.usersettings;

import com.atlassian.crowd.event.user.UserCreatedEvent;
import com.atlassian.crowd.model.user.User;
import com.atlassian.event.api.EventListener;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Batch Email feature discovery should only be shown to existing, not new users. This class provides a listener
 * for {@link UserCreatedEvent}s so that when a new user is created we can set their settings such that they will never
 * see the Batch Email feature discovery.
 */
public class UserCreatedEventListener {

    private static final Logger log = LoggerFactory.getLogger(UserCreatedEventListener.class);

    private final BatchEmailFeatureDiscovery featureDiscovery;
    private final UserService userService;

    public UserCreatedEventListener(BatchEmailFeatureDiscovery featureDiscovery,
                                    UserService userService) {
        this.featureDiscovery = featureDiscovery;
        this.userService = userService;
    }

    @EventListener
    public void onUserCreated(final UserCreatedEvent event) {
        User user = event.getUser();
        ApplicationUser stashUser = userService.getUserByName(user.getName(), true);
        if (stashUser != null) {
            log.debug("Setting batch email feature discovery to never show for user {}", stashUser.getName());
            featureDiscovery.setNeverShowFeatureDiscovery(stashUser);
        }
    }
}
