package com.atlassian.stash.internal.commit;

import com.atlassian.stash.internal.AbstractHibernateDao;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Nonnull;

import java.util.Collections;

import static com.atlassian.stash.internal.HibernateUtils.initialize;

/**
 * @since 2.11
 */
@Repository("commitDiscussionDao")
public class HibernateCommitDiscussionDao
        extends AbstractHibernateDao<Long, InternalCommitDiscussion>
        implements CommitDiscussionDao {

    @Autowired
    public HibernateCommitDiscussionDao(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    @Override
    public void delete(InternalCommitDiscussion entity) {
        throw new UnsupportedOperationException("CommitDiscussions share the lifecycle of their repository and cannot be deleted.");
    }

    @Override
    public InternalCommitDiscussion findByRepositoryAndCommit(int repositoryId, @Nonnull String commitId) {
        return initialize((InternalCommitDiscussion) session().createCriteria(InternalCommitDiscussion.class)
                .add(Restrictions.eq("repository.id", repositoryId))
                .add(Restrictions.eq("commitId", commitId))
                .uniqueResult());
    }

    @Override
    public InternalCommitDiscussion update(InternalCommitDiscussion entity) {
        throw new UnsupportedOperationException("CommitDiscussions are immutable and cannot be updated.");
    }

    @Override
    protected Iterable<Order> getImplicitOrder() {
        return Collections.singleton(Order.asc("id")); //There's really no useful ordering for commit discussions
    }
}
