package com.atlassian.stash.internal.scm.git;

import com.atlassian.bitbucket.user.SimplePerson;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.Person;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;

/**
 * Represents the value to be used when committing to git, such as merges.
 *
 * @since 3.0
 */
public enum AuthorNameType {
    DISPLAYNAME {
        @Override
        protected String getName(ApplicationUser author) {
            return author.getDisplayName();
        }
    },
    USERNAME;

    /**
     * @param author an author who might be a {@link ApplicationUser}
     * @return an updated person that respects the value of this
     */
    @Nonnull
    public Person convert(@Nonnull Person author) {
        // We only need to worry about StashUsers, otherwise we only have name anyway
        if (author instanceof ApplicationUser) {
            return new SimplePerson(getName((ApplicationUser) author), author.getEmailAddress());
        }
        return author;
    }

    @Nonnull
    public static AuthorNameType parseConfig(String order) {
        try {
            return valueOf(StringUtils.upperCase(order));
        } catch (RuntimeException ignored) {
            // Do nothing
        }
        return AuthorNameType.DISPLAYNAME;
    }

    protected String getName(ApplicationUser author) {
        return author.getName();
    }
}
