package com.atlassian.stash.internal.user;

import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.stash.experimental.user.RepositoryPermission;
import com.atlassian.stash.internal.HibernateUtils;
import com.atlassian.stash.internal.Initializable;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;

import javax.annotation.Nonnull;

import static com.google.common.base.Preconditions.checkNotNull;

public class InternalGrantedRepositoryPermission extends InternalPermittedEntity implements RepositoryPermission, Initializable {
    private Repository repository;

    public InternalGrantedRepositoryPermission(@Nonnull Repository repository, int weight) {
        super(weight);
        this.repository = checkNotNull(repository, "repository");
    }

    @Nonnull
    @Override
    public Repository getRepository() {
        return repository;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(repository, permission);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        final InternalGrantedRepositoryPermission other = (InternalGrantedRepositoryPermission) obj;
        return Objects.equal(this.repository, other.repository) && Objects.equal(this.permission, other.permission);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("repository", repository)
                .add("permission", permission)
                .toString();
    }

    @Override
    public void initialize() {
        repository = HibernateUtils.initialize(getRepository());
    }
}
